C# - 8 - How to define a 'constant' at runtime.

[C# 2.0]

Sometimes you want to define a variable that remains constant and unchangable. It's pretty easy when you know in advance what that variable should be set to as you can declare it as a class-wide const field.

.

But what if you don't know until run time what the value should be? Try to assign a value in the constructor and you'll get a compiler error. The answer is simple enough: define a class-wide readonly field.

… followed later in the constructor by an assignment.

The value can be changed as many times as you like whilst still in the constructor, but try and change the value outside the constructor and you'll get a compiler error (just like a traditional const).

.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License