Home > Code Analysis > Code Issues – Redundant field initialization

Code Issues – Redundant field initialization

May 20th, 2011


The redundant field initialization code issue of type ‘dead code‘ highlights unecessary initialization of fields that can be safely removed (because the common language runtime initializes all fields to their default values, regardless of their type). Value types are initialized to 0 and reference types are initialized to null. Explicitly initializing a field to its default value is redundant, degrades performance and adds to maintenance costs.

When you expressly initialize your fields, the compiler creates code to set the value of the fields and includes that code as part of your object initialization. When you instantiate an object using the new keyword, the following sequence happens:

  1. Your fields are allocated
  2. The fields are initialized by the CLR
  3. The code for the object constructor is performed

The problem is that if you explicitly initialized your fields, the constructor code will initialize your variables twice. This is not a big deal in most cases, but if those objects are instantiated many times, the performance impact may be noticeable.

Performing these kinds of tests when fields are initialized explicitly, shows the following result:

  • Creating an object and not initializing fields ~1013 ms (100%)
  • Creating an object and explictly initializing fields ~1124 ms (110%)

As you can see, there may be a noticeable performance hit.


CodeRush Redundant Field Initialization Sample

How to fix:

  • Apply the Remove Redundant Assignment code fix:

CodeRush - Redundant field initialization code issue

Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: any
Updated: Nov/12/2012
ID: C100

Similar Posts: