Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
- public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
- void Calculate(int Z)
- const int X = 10, X1 = 50;
- const int Y = X + X1; //no error, since its evaluated a compile time
- const int Y1 = X + Z; //gives error, since its evaluated at run time
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
- const MyClass obj1 = null;//no error, since its evaluated a compile time
- const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
- class MyClass
- readonly int X = 10; // initialized at the time of declaration
- readonly int X1;
- public MyClass(int x1)
- X1 = x1; // initialized at run time
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.
A Static Readonly type variable’s value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable’s value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime. Let’s understand it practically.
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
In the static readonly case, the containing class is allowed to modify it only
- in the variable declaration (through a variable initializer)
- in the static constructor (instance constructors, if it’s not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.