C#


CSHARP.TYPE.ARRAYTOSTRING : toString on Array (C#)

要旨

ToString() is called over an array.

Arrays are instances of System.Object in C#. As a consequence, all methods of System.Object can be invoked on arrays, However, this is not always sensible. In particular, calls to ToString() yield a string derived from the unique identifier of the object, which is likely to be useless for the programmer and not her intent when she called ToString().

It is possible that this warning is the consequence of refactoring, that replaced a collection class with an array but left the method calls unchanged.

プロパティ

クラス名 toString on Array (C#)
日本語クラス名 toString on Array (C#)
クラス分類 信頼性 (reliability)
ニーモニック CSHARP.TYPE.ARRAYTOSTRING
カテゴリー
CWE CWE:440 Expected Behavior Violation
対応言語 C# で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="toString on Array (C#)"

using System;

namespace DocumentationExamples
{

    public class CallsOnArray
    {
        private static CallsOnArrayA[] array;
        public static void Main(string[] args)
        {
            array = new CallsOnArrayA[args.Length];
            for (int pos = 0; pos < args.Length; pos++)
                array[pos] = new CallsOnArrayA(args[pos]);
            Foo(array);
            Console.WriteLine(array);  // "toString on Array (C#)" warning issued here 
                                       // - call is inside Console.WriteLine() 
        }
        private static void Foo(object o)
        {
            string s = o.ToString();   // "toString on Array (C#)" warning issued here 
            Console.WriteLine(s);
        }
    }
  
    public class CallsOnArrayA
    {
        private int f;
        public CallsOnArrayA(string s)
        {
            f = s.Length;
        }
        public override string ToString()
        {
            return f.ToString();
        }
    }
}

One solution is to use a loop:

for (int pos = 0; pos < array.Length; pos++)
    Console.WriteLine(array[pos]);

解決法

Replace the call with a call to that return a string with the elements of array or with an explicit iteration over the elements of the array.

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

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