The value of a static readonly field is set at runtime; therefore, the value can be modified by the containing class. On the other hand, the value of a const field is set to a compile-time constant.
In the case of static readonly, the containing class is allowed to modify the value only:
in the variable declaration (via a variable initializer)
in the static constructor (or instance constructors for non-static)
Typically, static readonly is used either when the value is unknown at compile time or if the type of the field is not allowed in a const declaration.
Also, instance readonly fields are allowed.
Note: for reference types, in both cases—static and instance—the readonly modifier only prevents assignment of a new reference to the field. It does not specifically make the object pointed to by the reference immutable.
Example:-
class TestProgram
{
public static readonly Test test = new Test();
static void Main (string[] args)
{
test.Name = "Application";
test = new Test();
// Error: A static readonly field cannot
// be assigned to (except in a static constructor
// or a variable initializer).
}
}
class Test
{
public string Name;
}
Wednesday, February 9, 2011
Subscribe to:
Posts (Atom)