Const vs Static in C# ?

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.

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;
}

On the other hand, if Test were a value type, then assignment to test.Name would be an error.

Leave a Reply

Your email address will not be published. Required fields are marked *