M G Vinod Kumar\’s Technology Blog

August 3, 2006

DateTime and IsEmpty

Filed under: .NET — mgvinod @ 11:29 am

I ran into a problem of checking whether a given DateTime is empty or not. Since DateTime is a value type, it is is initialised to {1/1/0001}(which is the MinValue), so checking for null reference won’t make sense, unless you are using NullableTypes. I did a search on google and ran into Eric Gunnerson’s post. He suggests using a new struct which checks for the emptiness.

public struct EmptyDateTime
{
    DateTime dateTime;

public EmptyDateTime(DateTime dateTime)
    {
        this.dateTime = dateTime;
    }

public bool IsEmpty
    {
        get
        {
            return dateTime == DateTime.MinValue;
        }
    }

public static explicit operator DateTime(EmptyDateTime emptyDateTime)
    {
        if (emptyDateTime.IsEmpty)
            throw new InvalidOperationException("DateTime is Empty");
        return emptyDateTime.dateTime;
    }

public static implicit operator EmptyDateTime(DateTime dateTime)
    {
        return new EmptyDateTime(dateTime);
    }

public static EmptyDateTime Empty
    {
        get
        {
            return new EmptyDateTime(DateTime.MinValue);
        }
    }
}

For those who are interested in the actual post:http://blogs.msdn.com/ericgu/archive/2004/03/23/95011.aspx

Advertisements

Blog at WordPress.com.