Skip to content

Latest commit

 

History

History
79 lines (59 loc) · 1.59 KB

GU0004.md

File metadata and controls

79 lines (59 loc) · 1.59 KB

GU0004

Assign all readonly members

Topic Value
Id GU0004
Severity Hidden
Enabled True
Category Gu.Analyzers.Correctness
Code ConstructorAnalyzer

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...")]