Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a DateTime object immutable (declare as const) in C#?

I have attempted the following code which will not work

private const DateTime newDateTime = new DateTime(1,1,1,1,1,1);

to which the compiler states "DateTime variable cannot be declared as const".

I am wondering how to make this object immutable, as i do not want to be able to change it anywhere by mistake. This value will be used as a check value to compare other DateTime objects to.

Thanks for any help.

like image 432
jordan Avatar asked Nov 05 '12 20:11

jordan


1 Answers

Make it static and mark with readonly keyword, i.e.:

private static readonly DateTime newDateTime = new DateTime(1,1,1,1,1,1);
like image 56
Kirill Polishchuk Avatar answered Nov 11 '22 17:11

Kirill Polishchuk