C#


CSHARP.STRUCT.UWFIELD : Field Never Written (C#)

Summary

A field is never written.

Fields constitute the state of an object, that is, they are meant to store information that survives across method calls. It is hence useless to store information in a field that is never read. Moreover, that behavior is actually harmful, since writing into a useless field hinders the garbage collector. It is also pointless to read data from a field that is never written, since the default value for the field will be found there. Note that there are situations when a field is written by reflection, which cannot be understood by analyzer, in general. This is often the case of fields auto-wired through dependency injection. The analyzer knows some specific patterns, typically marked through code annotations, but cannot foresee all possibilities.

Properties

Class Name Field Never Written (C#)
Significance reliability
Mnemonic CSHARP.STRUCT.UWFIELD
Categories
CWE CWE:456 Missing Initialization of a Variable
Availability Available for C# only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Field Never Written (C#)"

Example

using System;

namespace DocumentationExamples
{
  public class FieldAccess
  {
    private int f1;                            // Field Never Written (C#) warning issued here
    private readonly object f2 = new object(); // Field Never Read (C#) warning issued here
    private float f3;                          // Unused Field (C#) warning issued here

    public FieldAccess(){
      Console.WriteLine(f1);
    }

    public static void Main(string[] args){
      new FieldAccess();
    }
  }
}

In this example, all three fields are useless and could be removed, reducing the memory footprint of class instances.

Resolution

Remove all fields that are never read or never written.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.