C#


CSHARP.STRUCT.UNFLD : Unnecessary Field (C#)

Summary

One of the following.

Properties

Class Name Unnecessary Field (C#)
Significance reliability
Mnemonic CSHARP.STRUCT.UNFLD
Categories
CWE CWE:563 Assignment to Variable without Use
  CWE:1126 Declaration of Variable with Unnecessarily Wide Scope
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="Unnecessary Field (C#)"

Example

namespace DocumentationExamples
{

    public class ImproperField
    {
        public static void Main(string[] args)
        { }

        private int[] array = new int[100];
        private int counter;  // "Unnecessary Field (C#)" warning issued here
                              // - 'counter' should be replaced by local variables.

        public void Clear()
        {
            for (counter = 0; counter < array.Length; counter++)
                array[counter] = 1;
            counter = 0;      // "Unnecessary Field (C#)" warning issued here
                              // - value never used
        }
        
        private int field1;   // "Unnecessary Field (C#)" warning issued here
                              // - field1 only used in constructors
        public ImproperField(){
            field1 = 0;
            field1 = field1+1;
        }
    }
}

These issues can be resolved by removing the counter field (using a local variable instead), and by marking field1 as readonly.

namespace DocumentationExamples
{

    public class ImproperField
    {
        public static void Main(string[] args)
        { }

        private int[] array = new int[100];

        public void Clear()
        {
            for (int counter = 0; counter < array.Length; counter++)
                array[counter] = 1;
        }
        
        private readonly int field1;
        public ImproperField(){
            field1 = 0;
            field1 = field1+1;
        }
    }
}

Resolution

Use variables local to the methods and the constructors instead of fields.

Relevant Configuration File Parameters

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