Thursday, 10 October 2013

What is the difference between const and static readonly in C#

The distinction is that the worth of a static readonly field is about at run time, and may therefore be changed by the containing category, whereas the worth of a const field is about to a compile time constant.

In the static readonly case, the containing category is allowed to switch it solely

in the variable declaration (through a variable initializer)

in the static constructors(instance constructors, if it isn't static)

static readonly is often used if the kind of the sphere isn't allowed during a const declaration, or once the worth isn't proverbial at compile time.

Instance readonly fields also are allowed.

Remember that for reference sorts, in each cases (static and instance) the readonly modifier solely prevents you from distribution a replacement relevancy the sphere. It specifically doesn't create immutable  the item pointed to by the reference.

class Program
{
    public static readonly Test test = new Test();
    static void Main(string[] args)
{
test.Name = "Program";
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;

}


0 comments:

Post a Comment