C# Extension Methods – Three useful extension methods

A technique to raise the level of abstraction is to create a “domain specific language”.

Instead of cluttering high level code with if statements, nested for loops or switch statement, think about what you really want to say.

Stop writing == null, why not write a simple extension method called IsNull and IsNotNull (this even removes an almost unreadable !).

The third statement I called OrElse, comparable to Coalesce in SQL Server. In case a value is null (happens only in production ;-)) then this extension method tries one of the other values that it receives as arguments and returns the first value that is not null.

public static class BasicExtensions {

    public static bool IsNull<T>(this T obj)
    {
        return ( obj == null );
    }

    public static bool IsNotNull<T>(this T obj)
    {
        return ( obj != null );
    }

    public static T OrElse<T>(this T obj, params T[] otherValues)
    {
        if ( obj.IsNotNull() )
            return obj;

        return otherValues.Where(value => value.IsNotNull()).FirstOrDefault();
    }
}
Advertisements

About this entry