views:

244

answers:

4

Scenario

Consider the following code snippet.

        string s = "S";
        string s1 = "S";
        string s2 = string.Empty;
        switch (s)
        {
            case "S":
                s1 = "StringComparison";
                break;
            default:
                break;
        }

        switch (s[0])
        {
            case'S':
                s2 = "StringCOmpare2";
                break;
            default:
                break;
        }

the first switch case, results in a stringcomparison within IL.

But the second switch case, does not result in a stringcomparison within IL.

Can anyone justify this?

+13  A: 

Because on the second switch you're are not doing a String comparison, you're doing a Char comparison.

Paulo Santos
+2  A: 

Your second switch statement isn't using a string, but a single char. Hence, no string comparison.

Thorarin
+3  A: 

The easiest answer is that you're not doing a string comparison in the second block; you're comparing two characters.

However, you're right in that the two code blocks are functionally equivalent. A good optimizing compiler should be able to detect that 's' is a fixed-length string, and rewrite it not to use a full string comparison.

Michiel Buddingh'
+2  A: 

You're accessing the string via its indexer which returns a char and so lets you use the string as if it was an array of chars.

So whar you're doing is a char comparison. Using the apostrophe for the 'S' also tells you that you're using 'S' as a char and not as a string.

VVS