dotnet / dotnet/dotnet-api-docs
DateTime.MinValue has very odd interactions with Value and unclear, undocumented requirements
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
Someone asked a question on reddit about some odd behavior they were seeing when manipulating the `MinDate` property of a `DateTimePicker`. They set `MinDate` to `DateTime.MinValue`, then later tried to set `Value` to the same value. However, they got an exception informing them that the value was out of range. When I was poking at it, I managed to get an error with a different date that told me `MinDate` must be set to a date later than 1753.
When I examined the code for `DateTimePicker` it became clear. There is some validation logic that throws if the `MinDate` value is earlier than 1753 because of "problems with that year". (I think the author got confused, 1582 is the 'strange' year in Gregorian.) So why doesn't it throw when I set it the first time? Well, the first thing it does is compare the current backing field to the new value and it bypasses all logic if they are the same. The control itself initializes the backing field to `DateTime.MinValue`. So even though that is an *invalid* value for the property, it is valid *as long as the property has not yet been changed*. But bad things happen if you later try to set `Value` to `DateTime.MinValue`: the getter for `MinDate` defers to an internal method that returns a date in 1753.
This entails multiple documentation changes:
* `DateTimePicker.MinDate` should document that it throws an exception if you try to set it to a date before 1753.
* It casually mentions this date as the default, but does not clarify dates earlier than this are invalid.
* `DateTimePicker.MinDate` should document it actually won't throw that exception if you try to set it to `DateTime.MinValue` if and only if you haven't set it to another value. (Or the WinForms team should correct this error, but it's probably set in stone 'for historic reasons' at this point.)
* `DateTimePicker.Value` should document that it will throw if you try to set a date before 1753 even if, because of the last point, you've set `DateTimePicker.MinDate` to `DateTime.MinValue`.
* It currently indicates it throws if the value you set is less than `DateTimePicker.MinDate`, but since you can set `DateTimePicker.MinDate` to an invalid value that isn't quite true. (Or the WinForms team could correct this error.)
* It seems like the field `DateTimePicker.MinDateTime` is the appropriate minimum value for these fields, but I've been using .NET since 2003 and today is the first time I've noticed it, it's unmentioned in any of the above documentation despite being the basis for coercion and validation.
Contributor guide
Assessment
This issue has not been assessed yet.