Skip to content

Latest commit

 

History

History
97 lines (75 loc) · 2.56 KB

File metadata and controls

97 lines (75 loc) · 2.56 KB
title description ms.date f1_keywords helpviewer_keywords author ms.author dev_langs
IDE0064: Make struct fields writable
Learn about code analysis rule IDE0064: Make struct fields writable
09/30/2020
IDE0064
IDE0064
gewarren
gewarren
CSharp

Make struct fields writable (IDE0064)

Property Value
Rule ID IDE0064
Title Make struct fields writable
Category CodeQuality
Subcategory Language rules (modifier preferences)
Applicable languages C#

Overview

This rule detects structs that contain one or more readonly fields and also contain an assignment to this outside of the constructor. The rule recommends converting readonly fields to non-read only, that is, writable. Marking such struct fields as readonly can lead to unexpected behavior, because the value assigned to the field can change when this is assigned outside the constructor.

Options

This rule has no associated code-style options.

Example

// Code with violations
struct MyStruct
{
    public readonly int Value;

    public MyStruct(int value)
    {
        Value = value;
    }

    public void Test()
    {
        this = new MyStruct(5);
    }
}

// Fixed code
struct MyStruct
{
    public int Value;

    public MyStruct(int value)
    {
        Value = value;
    }

    public void Test()
    {
        this = new MyStruct(5);
    }
}

Suppress a warning

If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable IDE0064
// The code that's violating the rule is on this line.
#pragma warning restore IDE0064

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.IDE0064.severity = none

To disable this entire category of rules, set the severity for the category to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-CodeQuality.severity = none

For more information, see How to suppress code analysis warnings.

See also