Export (0) Print
Expand All

Do not initialize unnecessarily

TypeName

DoNotInitializeUnnecessarily

CheckId

CA1805

Category

Microsoft.Performance

Breaking Change

Non Breaking

A static or instance constructor initializes a field to its default value. This rule ignores Managed C++ assemblies.

The common language runtime initializes all fields to their default values before running the constructor. In most cases, initializing a field to its default value in a constructor is redundant, which degrades performance and adds to maintenance costs. One case where it is not redundant occurs when the constructor calls another constructor of the same class or a base class constructor and that constructor initializes the field to a non-default value. In this case, changing the value of the field back to its default value can be appropriate.

To fix a violation of this rule, remove the field initialization from the constructor. Note that the C# compiler that is included with .NET Framework 2.0 removes these unnecessary initializations when the optimize option is enabled.

You can also convert the field initialization to an assert as shown below:

Debug.Assert(field == 0); 

This will comply with the rule while making it clear to programmers working with the code that the field is already initialized. This will present a more familiar model to programmers who are used to working in multiple languages.

Suppress a warning from this rule if the constructor calls another constructor in the same or base class that initializes the field to a non-default value. It is also safe to suppress a warning from this rule, or disable the rule entirely, if performance and code maintenance are not priorities.

The following example shows a type that contains multiple violations of the rule.

using System;

namespace PerformanceLibrary
{
   class InitializeUnnecessarily
   {
      bool b1;
      bool b2;
      int i;
      double d;
      string s;

      InitializeUnnecessarily()
      {
         b1 = true;

         // The following field assignments are violations of this rule.
         b2 = false;
         i = 0;
         d = 0;
         s = null;
      }

      InitializeUnnecessarily(string s) : this()
      {
         // Exclude the warning for the following statement.
         b1 = false;

         this.s = s;
      }
   }
}

Community Additions

ADD
Show:
© 2014 Microsoft