Difference between const and readonly in c#
Following are the difference between const and readonly .
Const:
Following are the difference between const and readonly .
Const:
1.const can only be initialized at the declaration of the field. 2.const is static by default. 3.Value is evaluated at compile time.Readonly :
1.Readonly can be initialized either at the declaration or in a constructor. 2.Value is evaluated at run time. 3.Readonly fields can have different values depending on the constructor used.Example of const and readonly keywords in c# :
class MyClass
{
public readonly int y = 20; // Initialize a readonly field
public readonly int z;
public const int c1 = 5; // Initialize a const
public MyClass()
{
z = 24; // Initialize a readonly instance field in constructor.
}
}