Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 797
MadBoy Avatar asked Mar 16 '10 09:03

MadBoy


People also ask

What is the DateTime MinValue?

The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar. MinValue defines the date and time that is assigned to an uninitialized DateTime variable.

What is DateTime Maxvalue in C#?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.

How do I get the earliest date in C#?

You can do this immediately with LINQ using Enumerable. Min . DateTime minDate = dateCollection. Min();

Can we assign null to DateTime in C#?

Using the DateTime nullable type, you can assign the null literal to the DateTime type.


1 Answers

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.

like image 95
Heinzi Avatar answered Sep 30 '22 13:09

Heinzi