Reputation: 419
When I compare a DateTime variable with SqlDateTime.MinValue:
if (StartDate > SqlDateTime.MinValue)
{
// some code
}
I get the following runtime exception if StartDate is < SqlDateTime.MinValue:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
This can be easy solved with a small change:
if (StartDate > SqlDateTime.MinValue.Value)
{
// some code
}
I understand that in the first code snippet I'm comparing apples to oranges. What I don't understand is the exception message. It seems like I'm assigning a DateTime value to a SqlDateTime variable.
What am I missing?
Upvotes: 3
Views: 2558
Reputation: 1
From SqlDateTime Structure on MSDN:
SqlDateTime structure
Represents the date and time data ranging in value from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds to be stored in or retrieved from a database. The SqlDateTime structure has a different underlying data structure from its corresponding .NET Framework type, DateTime, which can represent any time between 12:00:00 AM 1/1/0001 and 11:59:59 PM 12/31/9999, to the accuracy of 100 nanoseconds. SqlDateTime actually stores the relative difference to 00:00:00 AM 1/1/1900. Therefore, a conversion from "00:00:00 AM 1/1/1900" to an integer will return 0.
Upvotes: 0
Reputation: 10184
The .NET native DateTime type (to be specific, its a structure) holds a broader range of possible values than the SqlDateTime data type can support. More specifically, a DateTime value can range from 01/01/0000 to a theoretical 12/31/9999.
When the compiler tries to coerce the types for comparison, it attempts to put a DateTime value (MinValue.Value) that's outside (below or 'before' in context) the range supported by SqlDateTime - hence the overflow.
Upvotes: 2