开发者

DateTime.MinValue vs new DateTime() in C#

When getting SQL DateTime Resharper suggests to use new DateTime() when value is DBNull.Value. I've always used DateTime.MinValue. Which is the proper way?

DateTime varData = sqlQueryResult["Data"] is DateTime ? (DateTime) sqlQueryResult["Data"] : new DateTime开发者_如何学运维();


From the documentation of DateTime.MinValue:

MinValue defines the date and time that is assigned to an uninitialized DateTime variable.

Thus, the resulting date will be the same. Since DateTime is a value type, both options should be equivalent. Personally, I prefer to write DateTime.MinValue, since it's self-documenting.

PS: You might want to consider using nullable types (DateTime?), if your data can contain (meaningful) null values.


Usually, I would handle the NULL case explicitly. Something along these lines:

if (!sqlQueryResults.IsNull("Data"))
    DoComputationDependantOnDateTime((DateTime) sqlQueryResults["Data"]);

In some cases, it might make sense to perform the logic even if no data is present. In such cases, only you know what default value to start from. Likely candidates:

  • DateTime.MinValue
  • DateTime.MaxValue
  • DateTime.Now

I would never use new DateTime() as it has very poor readability. What does that statement return? You (and future developers on the project) might have to look into the documentation to figure out what the value is initialized to.


I would say to always use MinValue because then you know exactly what value is in it. When you simply use new DateTime() you are initializing it to hold a value, but not specifying what value to place into it. It is also a lot cleaner and clearer to explicitly put a value into it.


Default value of DateTime is the DateTime.MinValue, so I guess it doesn't matter which of these you use ;)


There is no "proper" way. There is a convention that people set up and that the team follows.

DateTime.MinValue and new DateTime () are valid definitions for a null, if the developer in charge determines so.


The most maintainable way of representing a null value would be to use a Nullable<DateTime> i.e. DateTime?. That way the null value is clearly represented as a non-value instead of a magic value that needs special treatment.

(The null value of course also needs special treatment, but it's much harder to overlook.)

If you use a magic value to represent null values, no value is much better than any other. You can use DateTime.MinValue or new DateTime() (which give the same result), or you can use any arbitrary value that is outside the range that your application is using.

A value like DateTime.MinValue has a slight advantage as it's already defined as a constant, on the other hand you can define your own constant that has a slightly better name, for example:

public const DateTime DateThatMeansNull = new DateTime(1685, 3, 21);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜