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:

And of course, why insert the min date in the first place?
No comments:
Post a Comment