Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 |
A field of a class is explicitly initialized to the default value of that field's type.
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.
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;
}
It is always safe to suppress the warning, as the warning simply highlights potentially unnecessary code and work that may be avoided.
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.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register now