Skip to content

Latest commit

 

History

History
80 lines (61 loc) · 1.83 KB

GU0021.md

File metadata and controls

80 lines (61 loc) · 1.83 KB

GU0021

Calculated property allocates reference type

Topic Value
Id GU0021
Severity Hidden
Enabled True
Category Gu.Analyzers.Correctness
Code PropertyDeclarationAnalyzer

Description

Calculated property allocates reference type.

Motivation

Using expression body for allocating reference types may be a performance issue or a bug. The bug can be due to different instance from each call.

public class Foo
{
    public ExpensiveAllocation Bar => new ExpensiveAllocation();
}

How to fix violations

Fix by either:

  1. Convert the property to a get-only propert using the code fix.
public class Foo
{
    public Foo()
	{
		Bar = new ExpensiveAllocation();
	}
    public ExpensiveAllocation Bar { get; }
}
  1. Change to a method
public class Foo
{
    public ExpensiveAllocation Bar() => new ExpensiveAllocation();
}

Configure severity

Via ruleset file.

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

Via #pragma directive.

#pragma warning disable GU0021 // Calculated property allocates reference type
Code violating the rule here
#pragma warning restore GU0021 // Calculated property allocates reference type

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

#pragma warning disable GU0021 // Calculated property allocates reference type

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("Gu.Analyzers.Correctness", 
    "GU0021:Calculated property allocates reference type", 
    Justification = "Reason...")]