How will you make it if you never even try?

March 21, 2010

Some nice Nullable extensions

Filed under: C# — charlieflowers @ 7:11 am

Hey, I just banged out something nice and thought I’d share it. Some convenient extensions on Nullable.

I ran into a case where I have an object with a property of

 Nullable<DateTime> 

. If the value is not null, I want to call ToShortDateString() on it. But if it *is* null, then I merely want to return empty string.

It was really a pain in the ass to do it before the extension methods, because it looked something like this:

string x;

if(theObject.TheDateProperty.HasValue)
{
   x = theObject.TheDateProperty.ToShortDateString();
}
else
{
   x = string.Empty;
}

With the extension methods I wrote, it can now be much nicer:

string x = theObject.TheDateProperty.Safe(d => d.ToShortDateString());

I love it when my language comes through for me. Anders is the man.

Here are the extension methods

public static class NullableExtensions
    {
        public static TReturn Safe<TType, TReturn>(this Nullable<TType> nullableValue, TReturn defaultValue, Func<TType, TReturn> func) where TType : struct
        {
            if (!nullableValue.HasValue) return defaultValue;

            return func(nullableValue.Value);
        }

        public static TReturn Safe<TType, TReturn>(this Nullable<TType> nullableValue, Func<TType, TReturn> func) where TType : struct
        {
            return nullableValue.Safe<TType, TReturn>(default(TReturn), func);
        }

        public static string Safe<TType>(this Nullable<TType> nullableValue, Func<TType, string> func) where TType : struct
        {
            return Safe<TType, string>(nullableValue, string.Empty, func);
        }
    }

Notice the specific one for a return type of String, that lets you avoid explicitly stating that the default should be “” all the time. I could definitely envision other specific Safe() methods being added for other types down the road.

Advertisements

Create a free website or blog at WordPress.com.