Through the series of articles, we are discussing about the Modifiers in C#. These modifiers are used to modify the behavior of the defined members.
const
and readonly
modifiers in C# are used to define constants and read only members. Let’s discuss little bit more about these modifiers in this article.
The const
Modifier
When we declare a variable in C#, we can modify the content of the variable anywhere in the program unless Access specifiers are mentioned. How to restrict to modify it’s value? The answer is using const
keyword.
const
keyword is used to define constant variables; whose values can not be changed throughout the program.
When you define a constant variable it’s value must be assigned or defined at the time of declaration itself. Hence, we can say this is a compile-time constant. That means, C# compiler will verify whether the constant variable is assigned to a value at the declaration. Otherwise, compiler will through the Error.
const
modifier can not be used on classes and it’s methods. This can be used only on properties of the class or variables defined in the functions.
Important thing is, we can not access const
members through the instances of the class. These are NOT instance variables. If you attempt to access the constant variables through the class objects; you will see the below Error:
Error 1 Member ‘Modifiers.Program.constVar’ cannot be accessed with an instance reference; qualify it with a type name instead
As I mentioned above, you are allowed to assign a value to constant variables ONLY at the time of declaring the variables. If you attempt to assign a value to the constant variable after it was defined; you will see the below Error:
Error 1 The left-hand side of an assignment must be a variable, property or indexer
The readonly
Modifier
A readonly
keyword is used to declare read only members or variables. Unlike const
modifier, readonly
modifier allows to define the members with values at the time of declaration or in the class constructors.
For example, if you define a readonly
member and assign a value at the time of declaration; the value can be modified in the class constructor. This is not the case for const
members; once the value is assigned to the const
members, the values can not be modified through out the program.
Once readonly
variable was defined, it is NOT allowed to modify the variable except in a class’s constructor. Otherwise, the compiler will throw the below Error.
Error 1 A readonly field cannot be assigned to (except in a constructor or a variable initializer)
The complete working example is here:
We will discuss more topics in my upcoming Articles.
(Raju)