C#


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

要旨

One of the following.

プロパティ

クラス名 Unnecessary Field (C#)
日本語クラス名 Unnecessary Field (C#)
クラス分類 信頼性 (reliability)
ニーモニック CSHARP.STRUCT.UNFLD
カテゴリー
CWE CWE:563 Assignment to Variable without Use
  CWE:1126 Declaration of Variable with Unnecessarily Wide Scope
対応言語 C# で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Unnecessary Field (C#)"

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;
        }
    }
}

解決法

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

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。