Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is not allowed to create datetime constant in .net?

Tags:

c#

.net

I want to create a datetime constant in .net but getting the error message

const DateTime dt = Convert.ToDateTime("02/02/2014"); 

'System.DateTime' cannot be declared const.

like image 482
Romil Kumar Jain Avatar asked Feb 25 '13 09:02

Romil Kumar Jain


People also ask

How accurate is DateTime now in C#?

From MSDN you'll find that DateTime. Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.

Is DateTime now static?

DateTime. Today is static readonly . So supposedly it should never change once (statically) instantiated.

What is a DateTime?

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. Time values are measured in 100-nanosecond units called ticks.


2 Answers

Even if you could declare a DateTime as const (which you can't, as other answers have indicated) you would have to use a compile-time constant as the value - and DateTime.Now most certainly isn't a compile-time constant.

This is valid though:

static readonly DateTime dt = DateTime.Now(); 

Note that this will be "whatever time the type initializer for the type ran" though. That's rarely a particularly useful value unless you ensure it's initialized on start-up, assuming that's what you're trying to measure...

like image 125
Jon Skeet Avatar answered Oct 05 '22 18:10

Jon Skeet


DateTime is not a native type in the C# language - it's a struct from the .Net libraries.

In C#, you can only create consts from the native language types, and you can only initialise them with values that can be calculated at compile-time. DateTime.Now cannot be calculated at compile time.

(The only reference type you can use with a const is a string, and that's because strings are handled specially.)

See http://msdn.microsoft.com/en-gb/library/e6w8fe1b%28v=vs.71%29.aspx

like image 28
Matthew Watson Avatar answered Oct 05 '22 20:10

Matthew Watson