What is Static ReadOnly?
In C#, 'static readonly' is used to declare a constant value that is shared among all instances of the class, and its value cannot be changed once it is initialized. It combines the features of both 'static' and 'readonly'.
When you use 'static readonly', the value must be assigned at the time of declaration or within a static' constructor of the class. After initialization, the value cannot be modified, and it remains the same throughout the program's execution.
Here's an example of using 'static readonly':
public class MyConstants
{
public static readonly int MaxValue = 100;
public static readonly string DefaultName;
static MyConstants()
{
// The static constructor is used to initialize static readonly members.
DefaultName = "John";
}
}
In this example, 'MaxValue' is a static readonly field, and its value is set to 100. 'DefaultName' is also a static readonly field, but its value is set within the static constructor of the class.
Static readonly fields are often used for values that should be constant throughout the program but are calculated at runtime or require more complex initialization logic than simple literals (like in the case of 'DefaultName' in the example above). They provide a way to enforce constant behavior while allowing more flexibility in how the constant value is determined.
Here's another example that demonstrates an error when attempting to assign a value to a 'readonly' variable in a different method..
As shown in the image below, a variable named 'ProductionYear' is declared as static readonly. While we can assign a value to this variable within the static constructor, any attempt to assign it within other methods or events will result in a compile-time error.