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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With