Monday, January 25, 2010

What is the difference between CONST and READONLY?

A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor.
Therefore readonly fields can have different values depending on the constructor used.For eg.
readonly int a;
public class()
{
a=1;
}
public class(string s)
{
a=5;
}
public class(string s, int i)
{
a=i;
}
A const field is a compile-time constant meaning that it is evaluated at compile time, the readonly field can be used for runtime constants which means value gets evaluated during runtime.

No comments: