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?
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 .
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.
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 .
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.
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); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With