65.9K
CodeProject is changing. Read more.
Home

IfNull Extension Method

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jul 3, 2012

CPOL

1 min read

viewsIcon

22481

An extension method that gives you a replacement if the Type is null.

Introduction

This tip explains how to implement and use a Generic IfNull Extension Method in your project.

Background

While working on my current C# project after completing an MS Access VBA project, I really missed the Nz function, so I set about creating one. I initially thought about using a static method but didn't like the idea of that as it wouldn't look nice in the code. I then read How does it work in C#? - Part 3 (C# LINQ in detail) by Mohammad A Rahman and it reminded me about Extension Methods so I gave it a go.

If you would like more extension methods there are some very useful ones in the article Extension Methods in .NET that I found to make sure I wasn't duplicating.

Using the code

In your project/solution, create a class and put in the following code:

using System.Text;
 
namespace MyExtensions
{
    public static class Extensions
    {           
       public static T IfNull<T>(this T source, T valueIfNull)
        {
            if (source is string)
            {
                string temp = source as string;
 
                if (!string.IsNullOrEmpty(temp))
                    return source;
                
                return valueIfNull;
            }
 
            if (source is StringBuilder)
            {
                StringBuilder temp = source as StringBuilder;
 
                if (temp == null)
                    return valueIfNull;
 
                if (temp.Length != 0)
                    return source;
 
                return valueIfNull;
            }
 
            if (source != null)
                return source;
 
            return valueIfNull;
        }
    }
}

With this extension method, you can add custom code to handle specific classes as I have done with the StringBuilder class. This example handles a zero length instance.

To use the extension method in your project, just reference the namespace and project/assembly and the method will be available to use like this:

string salutation = string.Empty;
 
Console.WriteLine (salutation.IfNull("Sir/Madam"));

Points of Interest

Changing the namespace of the class to System will allow you to use the extension throughout your project but I'm not sure if that is a good practice or not.