How to enable CA1820 for switch statement

I get the following FxCop error:

CA1820: Microsoft.Performance: replace the call to "string.operator == (string, string)" in "Program.Main ()" with the call to "String.IsNullOrEmpty".

 static void Main()
    {
        string str = "abc";

        switch (str)
        {
            case "":
                Console.WriteLine("Hello");
                break;
        }

        Console.ReadLine();
    }
+4
source share
4 answers

Hmm interesting question. If you look at ILSpy , you will see decompiled code as:

string str = "abc";
string a;
if ((a = str) != null && a == "")
{
    Console.WriteLine("Hello");
}
Console.ReadLine();

The reason it is converted to a block if-elseis because if the switch statement contains 5or is less than the 5case clause , then it will be treated like if - elsethat, otherwise the lookup table will be used. I'm not sure about the quantity 5, but this is what is shown in ILSpy)

a == "", , :

CA1820:

String.Length String.IsNullOrEmpty , . , Equals MSIL , IsNullOrEmpty Length . , Equals Length == 0 - . Length null, System.NullReferenceException. , ; false. null . .NET Framework 2.0 IsNullOrEmpty . Length ==, .

+3

Length , string.IsNullOrEmpty (str == "").

 string str = "abc";

        switch (str.Length)
        {
            case 0:
                Console.WriteLine("Hello");
                break;
        }

        Console.ReadLine();

IsNullOrEmpty switch string.Empty default.

if (string.IsNullOrEmpty(str))
{
    // related code section
}
else
{
    switch (str)
    {
        case "case1":
            Console.WriteLine("Hello");
            break;
        case "case2":
            Console.WriteLine("case2");
            break;
    }
}
+1

switch. .

if.

string str = "abc";
if (string.IsNullOrEmpty(str))
    Console.WriteLine("Hello");
0

You should use string.empty instead of "", but that probably won't solve the fxcop warning. I usually listened, but in this case it seems overly active, assuming you really need a switch / case pattern with strings. If you cannot suppress it for any reason (provided that the actual switch statement has many more cases), you can write a special if (String.IsNullOrEmpty (str)) before the case.

-1
source

All Articles