Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a class instance as a constant in C#?

Tags:

c#

.net

constants

I need to implement this:

static class MyStaticClass {     public const TimeSpan theTime = new TimeSpan(13, 0, 0);     public static bool IsTooLate(DateTime dt)     {         return dt.TimeOfDay >= theTime;     } } 

theTime is a constant (seriously :-), like π is, in my case it'd be pointless to read it from settings, for example. And I'd like it to be initialized once and never changed.

But C# doesn't seem to allow a constant to be initialized by a function (which a constructor is). How to overcome this?

like image 577
Ivan Avatar asked Jun 03 '11 18:06

Ivan


People also ask

What is the correct way to declare constant in C?

const datatype variable = value ; So to declared the constant we used const int var=10; is the correct way to declared the constant in the c programming language .

How do you declare a constant?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.

How do you declare a constant in a class in C ++?

To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .

How can a datatype be declared to be a constant type?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.


2 Answers

Using readonly instead of const can be initialized and not modified after that. Is that what you're looking for?

Code example:

static class MyStaticClass {     static readonly TimeSpan theTime;      static MyStaticClass()     {         theTime = new TimeSpan(13, 0, 0);     } } 
like image 51
ashelvey Avatar answered Sep 19 '22 01:09

ashelvey


Constants have to be compile time constant, and the compiler can't evaluate your constructor at compile time. Use readonly and a static constructor.

static class MyStaticClass {   static MyStaticClass()   {      theTime = new TimeSpan(13, 0, 0);   }    public static readonly TimeSpan theTime;   public static bool IsTooLate(DateTime dt)   {     return dt.TimeOfDay >= theTime;   } } 

In general I prefer to initialise in the constructor rather than by direct assignment as you have control over the order of initialisation.

like image 27
James Gaunt Avatar answered Sep 23 '22 01:09

James Gaunt