Reputation: 7728
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?
Upvotes: 0
Views: 552
Reputation: 19612
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.
Upvotes: 2
Reputation: 5919
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.
Upvotes: 3
Reputation: 48506
Your second switch statement isn't using a string, but a single char. Hence, no string comparison.
Upvotes: 2
Reputation: 11587
Because on the second switch you're are not doing a String comparison, you're doing a Char comparison.
Upvotes: 13