Switch on strings in C#


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">One of the developers on the team
recently asked about how switch on string really works… I thought I’d share that
discussion with you. "urn:schemas-microsoft-com:office:office" />


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">what kind of comparison is done if
the user writes code like this:


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial">string
firstname = “Daniel”;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial">string
lastname;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial">switch
(firstname) {


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">   case
“Daniel”:


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">           
lastname = “Herling”;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">           
break;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">   default:


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">           
lastname = “don’t know”;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial"> style="mso-spacerun: yes">           
break;


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-bidi-font-family: Arial">}


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">Will the switch statement use the
current culture info? Or will it simply do a String.Equals
comparison?


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">A: You can tell by looking at the
ILASM for this code that it does not call String.Equals() however the comparison
used by C#’s switch on string is functionally equivalent to String.Equals (and
the switch statement additionally allows null as a case constant and as the
value of the selector expression). The fact that we do string interning and
reference compares is just an optimization. style="mso-spacerun: yes">  Too see more information about string
interning and reference compares I suggest reading href="http://blogs.gotdotnet.com/cbrumme/PermaLink.aspx/7943b9be-cca9-41e1-8a83-3d7a0dbba270">CBrumme’s
excellent blog on the topic.


 

Comments (1)

  1. Eric Gunnerson says:

    IIRC, switch on string will switch to using a hashtable when the number of strings gets to be large enough that a hashtable is quicker than a series of comparisons.