What is the difference between const
and readonly
in C#?
When would you use one over the other?
There is notable difference between const and readonly fields in C#.Net
const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.
public const DateTime dt = DateTime.Today; //throws compilation error
public const string Name = string.Empty; //throws compilation error
public readonly string Name = string.Empty; //No error, legal
readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -
class A
{
public readonly int Id;
public A(int i)
{
Id = i;
}
}
Then readonly field can be initialised with instant specific values, as follows:
A objOne = new A(5);
A objTwo = new A(10);
Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.