0

Why DateTime.MinValue and DateTime.MaxValue are not const like int.MinValue and int.MaxValue? Why would C# do that?

I tried to take a look at struct DateTime but couldn't find any constructor that initializes these fields.

Imad
  • 7,126
  • 12
  • 55
  • 112
  • Are they different in the same version of .NET? Under what circumstances are they different? – Matt Oestreich Apr 14 '19 at 06:29
  • 1
    Possible duplicate of [Why does C# limit the set of types that can be declared as const?](https://stackoverflow.com/questions/441420/why-does-c-sharp-limit-the-set-of-types-that-can-be-declared-as-const) – Streamline Apr 14 '19 at 06:53
  • Only native types can be constants. [Why it is not allowed to create datetime constant in .net?](https://stackoverflow.com/questions/15063431/why-it-is-not-allowed-to-create-datetime-constant-in-net) – Theodor Zoulias Apr 14 '19 at 06:55

1 Answers1

3

In .NET only primitive types and strings can be constants.

I tried to take a look at struct DateTime but couldn't find any constructor that initializes these fields.

They are initialized in place: https://referencesource.microsoft.com/#mscorlib/system/datetime.cs,114

In practice, initialization of static fields will be generated in the static constructor:enter image description here

Fun fact:

In C# you can define decimal constants; however, decimal is not a primitive type. In the background these "constants" will also be compiled as static fields with a special DecimalConstant attribute: enter image description here

György Kőszeg
  • 17,093
  • 6
  • 37
  • 65
  • 2
    It might be worth modifying your first sentence to mention decimal, given that the later part contradicts it. It's also worth noting that there's a [`DateTimeConstantAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.datetimeconstantattribute?view=netframework-4.7.2) that *could* be used in the same way if C# ever wanted to support them. – Jon Skeet Apr 14 '19 at 07:09
  • @JonSkeet: I corrected the first sentence. And I did not know about the `DateTimeConstantAttribute`, thank you for the info. – György Kőszeg Apr 14 '19 at 07:16