CA1805: Do not initialize unnecessarily
Property | Value |
---|---|
Rule ID | CA1805 |
Title | Do not initialize unnecessarily |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | No |
Cause
A field of a class is explicitly initialized to the default value of that field's type.
Rule description
The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed.
How to fix violations
In most cases, the proper fix is to delete the unnecessary initialization.
class C
{
// Violation
int _value1 = 0;
// Fixed
int _value1;
}
In some cases, deleting the initialization may result in subsequent CS0649 warnings being issued due to the field retaining its default value forever. In such cases, a better fix may be to delete the field entirely or replace it with a property:
class C
{
// Violation
private static readonly int s_value = 0;
// Fixed
private static int Value => 0;
}
When to suppress warnings
It is always safe to suppress the warning, as the warning simply highlights potentially unnecessary code and work that may be avoided.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1805
// The code that's violating the rule is on this line.
#pragma warning restore CA1805
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1805.severity = none
For more information, see How to suppress code analysis warnings.