Search This Blog


difference between Constant And Readonly

What is the difference between constant and readonly?

Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

You can't use the static keyword with a const because it would be redundant. You can think of const as a subset of static.

Consts are static, not instance members.

public class Constant
public const int C = 12345;

public class ReadOnly
private readonly int r = 1; //variable initialization upon declaration is possible for readonly variables

public ReadOnly()
r = 2; //assignment to a readonly variable is possible in the constructor

public int R
get { return r; }
set { r = value; } //this line won't compile because r is declared a readonly

No comments: