Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve CA1820 for switch statement

Tags:

c#

.net

I am getting following FxCop error:

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

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

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

        Console.ReadLine();
    }
like image 806
Atul Sureka Avatar asked Oct 05 '22 04:10

Atul Sureka


1 Answers

Hmm interesting question. If you look at it in ILSpy you will see the decompiled code as:

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

The reason it is converting into if-else block is that, if the switch statement contains 5 or less then 5 case clause then it will be treated as if - else otherwise a lookup table will be used.(I am not sure about the number 5 but this is what is being shown in ILSpy)

Now it is complaining about a == "" and here is the description why it is complaining about it:

CA1820: Test for empty strings using string length

Comparing strings using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. This is because Equals executes significantly more MSIL instructions than either IsNullOrEmpty or the number of instructions executed to retrieve the Length property value and compare it to zero. You should be aware that Equals and Length == 0 behave differently for null strings. If you try to get the value of the Length property on a null string, the common language runtime throws a System.NullReferenceException. If you perform a comparison between a null string and the empty string, the common language runtime does not throw an exception; the comparison returns false. Testing for null does not significantly affect the relative performance of these two approaches. When targeting .NET Framework 2.0, use the IsNullOrEmpty method. Otherwise, use the Length == comparison whenever possible.

like image 197
Habib Avatar answered Oct 10 '22 03:10

Habib