Coder Perfect

default versus new DateTime() (DateTime)


Is there a compelling reason to pick one over the other?

DateTime myDate = new DateTime();


DateTime myDate = default(DateTime);

1/1/0001 12:00:00 AM is the same for both of them.

Asked by RJP

Solution #1

No, they’re the same.

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

Answered by Servy

Solution #2

You can only use default as a default value for a DateTime parameter in a method (DateTime).

The line below will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will result in the following output:

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

Answered by Tomer

Solution #3

No, that is not the case. Keep in mind that mdDate.Kind Equals DateTimeKind.Unspecified in both circumstances.

As a result, the following might be preferable:

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

myDate is an acronym for “my Date.” Because the Kind property is readonly, it cannot be modified once the constructor has been called.

Answered by Ben C

Solution #4

DateTime is a struct, which is the simplest way to comprehend it. When you initialize a struct, it is set to its smallest value, which is DateTime. Min

As a result, no difference exists between default(DateTime), new DateTime(), and DateTime.Min.

Answered by G.Busato

Post is based on