declaring a DateTime const

G

Guest

Hi folks,
I am trying to declare a datetime constant as follows:
(As a class member)

internal const DateTime m_FutureDate = new DateTime
(2199,1,1,0,0,0);

I am getting a compilation error:
The expression being assigned to 'm_FutureDate' must be
constant. Please let me know how to declare datetime
constants. thank you.
 
A

Andreas Håkansson

Mr.Anonymous ;)

The documentation for the "const" keyword states that a const has to be
one
of the following type: byte, char, short, int, long, float, double, decimal,
bool,
string, an enum type, or a reference type. You could use the readonly
keyword
to do what you want

internal readonly DateTime m_FutureDate =
new DateTime(2199,1,1,0,0,0);

The difference between readonly and const is that a const can only be
assigned
when being declared, where as a readonly variable can be assigned both when
being declared and in the constructor(s). This means you can provide a
different
value to a readonly variable depending on how the class as created.

Hope this helps,

//Andreas Håkansson
 
B

Bruno Jouhier [MVP]

Right. You should also use the static keyword in the declaration, so that
you get a single value for all instances instead of a new value for every
instance of your class:

internal static readonly DateTime FutureDate = new DateTime(2199,1,1,0,0,0);

Bruno.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top