C#

C#

Made by DeepSource

Fields initialized only in constructors can be made readonly CS-R1137

Anti-pattern
Major

The 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.

Bad Practice

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

Recommended

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