21 December 2010

Difference between const and static readonly keywords C#

Difference between const and static readonly keywords C#

If in your C# class you want to use a variable whose value will not change during the lifetime of that class, then you have
two options:

1. Use the "const" keyword: for e.g. public const int myVar = 100;

2. Use the "static readonly" keyword: for e.g. public static readonly int myVar = ConfigurationManager.AppSettings["value"];

The const variable has a limitation: it can ONLY be set during compile time. This means you cannot set its value using any code
logic, like getting its value from some config file, or from some "if" condition. Whereas the value of a static readonly field
can be set at run time, and can thus be modified by the containing class using any custom logic.

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)

No comments:

Post a Comment

Comments Welcome