Switch on strings in C#

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.