Pages

Friday, April 8, 2011

Solving Sql vs C# Minimum DateTime Issue using Extension Method

Do "DateTime.MinValue" in .NET, and you would get "1/1/0001 12:00:00 AM", the default value of DateTime variables. Try inserting it into SQL Server DB, and you will get an exception, because the minimum datetime in SQL Server is 01/01/1753. This is usually not a problem as most of the time the datetime variable is assigned with valid date.

The simplest way to solve it: As soon as we instantiate a DateTime var, assign its value to SqlDateTime.MinValue, like below:

DateTime dateTime = new DateTime();
dateTime = SqlDateTime.MinValue.Value;

However, won't it be much easier if the DateTime, itself, has a method that returns Sql min value? And, this is where we can use Extension methods. Here's a description from MSDN:

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type."
Creating extension method is very simple. You need to create a static class that has static method whose first parameter is preceded with this, and specifies what type the method will work on. In our case, it will look like:

public static class DateExtension
    {
        public static DateTime SqlValidDateTime(this DateTime d)
        {
            return SqlDateTime.MinValue.Value;
        }
    }

To use it is even simpler: 
This is definitely not the only way to do it. It reduces code redundancy, and makes code much cleaner if you are assigning SqlDateTime.MinValue after each datetime variable initialization. 
And of course, why insert the min date in the first place?

No comments:

Post a Comment