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

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: