Amazon.com Widgets

Switch on strings in C#

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.

 

what kind of comparison is done if the user writes code like this:

string firstname = “Daniel”;

string lastname;

 

switch (firstname) {

   case “Daniel”:

            lastname = “Herling”;

            break;

   default:

            lastname = “don’t know”;

            break;

}

Will the switch statement use the current culture info? Or will it simply do a String.Equals comparison?

 

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.  Too see more information about string interning and reference compares I suggest reading CBrumme’s excellent blog on the topic.

 

Published 14 August 03 11:50 by BradA
Filed under:

Comments

# Eric Gunnerson said on August 14, 2003 9:38 PM:
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.
New Comments to this post are disabled

Search

This Blog

Syndication

Page view tracker