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