new DateTime() vs default(DateTime)

C#DatetimeDefault

C# Problem Overview


Is there a reason to choose one of these over the other?

DateTime myDate = new DateTime();

or

DateTime myDate = default(DateTime);

Both of them are equal 1/1/0001 12:00:00 AM.

C# Solutions


Solution 1 - C#

No, they are identical.

default(), for any value type (DateTime is a value type) will always call the parameterless constructor.

Solution 2 - C#

If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

The following line will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will compile:

    private void MyMethod(DateTime syncedTime = default(DateTime))

Solution 3 - C#

The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified.

Therefore it may be better to do the following:

DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);

The myDate.Kind property is readonly, so it cannot be changed after the constructor is called.

Solution 4 - C#

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRJPView Question on Stackoverflow
Solution 1 - C#ServyView Answer on Stackoverflow
Solution 2 - C#TomerView Answer on Stackoverflow
Solution 3 - C#Ben CView Answer on Stackoverflow
Solution 4 - C#G.BusatoView Answer on Stackoverflow