The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
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)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object 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;
}
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it:
-- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
Const Keyword in C# .NET
Example: public const string abc = “xyz”;
Initialized only at declaration.
Value is evaluated at compile time and can not be changed at run time.
An attempt to change it will cause a compilation error.
Const is already kind of static.
Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types.
Readonly Keyword in C# .NET
Example: public readonly string abc;
Can be initialized in declaration code or consturctor code.
Value is evaluated at run time.
Can be declared as static or instance level attribute.
A read only field can hold a complex object by using the new keyword at run time.