# Wednesday, May 27, 2009

Convert DateTime to DateTime?

Back when .NET 1.1 was cool people would often use DateTime.MinValue to indicate that a date was actually empty. With .NET 2.0 can the Nullable<T> which allows you to create a nullable datetime. Ofcourse there is still plenty of old code out there, so when adding new code you may need to convert DateTime.MinValue to null. With extensions methods (.NET 3.5) you can implement an elegant solution.

The code below will allow you to write this:

DateTime old = DateTime.MinValue;

DateTime? current = old.ToNullable();

This is achieved with the following extension method:

public static class DateTimeExtension
{
    /// <summary>
    /// Examine the value of the DateTime, if the value is equal to DateTime.MinValue
    /// then the result is null, otherwise the supplied value is returned.
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static DateTime? ToNullableDateTime( this DateTime value )
    {
        if ( value == DateTime.MinValue )
        {
            return null;
        }
        else
        {
            return value;
        }
    }
}

#    Comments [0] |