GU0004

November 24, 2021 ยท View on GitHub

Assign all readonly members

TopicValue
IdGU0004
SeverityHidden
EnabledTrue
CategoryGu.Analyzers.Correctness
CodeConstructorAnalyzer

Description

Assign all readonly members.

Motivation

In the following code the readonly member B is never assigned.

public class Foo
{
    public Foo(int a)
    {
        this.A = a;
    }

    public int A { get; }

    public int B { get; }
}

How to fix violations

Assign a value to B in constructor or in initializer (showing borth in the example below):

public class Foo
{
    public Foo(int a)
    {
        this.A = a;
        this.B = 2;
    }

    public int A { get; }

    public int B { get; } = 3;
}

Configure severity

Via ruleset file.

Configure the severity per project, for more info see MSDN.

Via #pragma directive.

#pragma warning disable GU0004 // Assign all readonly members
Code violating the rule here
#pragma warning restore GU0004 // Assign all readonly members

Or put this at the top of the file to disable all instances.

#pragma warning disable GU0004 // Assign all readonly members

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("Gu.Analyzers.Correctness", 
    "GU0004:Assign all readonly members", 
    Justification = "Reason...")]