C# switch statements are hashed

Stum­bled upon an inter­est­ing ques­tion on Stack­Over­flow today regard­ing what goes on under the hood when you use the switch state­ment in C#.

Based on the answer by Bri­an Gideon (kudos for doing all that leg­work!), for the fol­low­ing code:

public static int Main(string[] args)
    switch (args[0])
        case "1": return 1;
        case "2": return 2;
        case "3": return 3;
    return 0;

the C# com­pil­er will:

  • if the num­ber of case state­ments is small then emit a sequen­tial equal­i­ty com­par­i­son;
  • if the num­ber of case state­ments is large then emit a Dic­tio­nary lookup.

Also, on a relat­ed ques­tion regard­ing if-else vs. switch state­ment, the updat­ed answer also seems to con­firm this find­ing (regard­ing the use of a string in the switch state­ment at least) and Jon Skeet’s com­ment to the answer by ‘ima’ sug­gests that the thresh­old is 6 before the com­pil­er decides to build a hash table, i.e. case state­ment count >= 7 then build dic­tio­nary.