readonly
CS-R1137The readonly
modifier can be applied to fields that are not initialized anywhere in a class and if initialized, it is either initialized inline or in the constructor.
This modifier prevents you from rewriting/overwriting its values and may even allow the runtime to perform additional optimizations.
Consider using this modifier when and where possible.
class C
{
private int x;
private int y;
public C()
{
// `x` is not modified anywhere outside `C()`.
x = 1;
}
public void M()
{
// `y` is initialized in a method.
// Cannot be marked as `readonly`.
y = 2;
}
}
class C
{
private readonly int x;
private int y;
public C()
{
// `x` is not modified anywhere outside `C()`.
x = 1;
}
public void M()
{
// `y` is initialized in a method.
// Cannot be marked as `readonly`.
y = 2;
}
}