<p>When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.</p>

<p>For example (and yes, I know, if you're doing this sort of thing it probably means your <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">object-oriented</a> (OO) architecture is iffy - this is just a contrived example!),</p>

<pre><code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code></pre>

<p>Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.</p>

<p>Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement <em>has</em> to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?</p>

[{'answer_id': 44921, 'author': 'Brian Ensink', 'author_id': 1254, 'author_profile': 'https://Stackoverflow.com/users/1254', 'pm_score': 8, 'selected': True, 'text': '<p>This is my original post, which sparked some debate... <strong>because it is wrong</strong>:</p>\n\n<blockquote>\n  <p>The switch statement is not the same\n  thing as a big if-else statement. \n  Each case must be unique and evaluated\n  statically.  The switch statement does\n  a constant time branch regardless of\n  how many cases you have.  The if-else\n  statement evaluates each condition\n  until it finds one that is true.</p>\n</blockquote>\n\n<hr>\n\n<p>In fact, the C# switch statement is <strong>not</strong> always a constant time branch.</p>\n\n<p>In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table.  However, in sparse cases as pointed out by <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259">Ivan Hamilton</a> the compiler may generate something else entirely.</p>\n\n<p>This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.</p>\n'}, {'answer_id': 44927, 'author': 'markus', 'author_id': 3498, 'author_profile': 'https://Stackoverflow.com/users/3498', 'pm_score': 2, 'selected': False, 'text': '<p>This is not a reason why, but the C# specification section 8.7.2 states the following:</p>\n\n<blockquote>\n  <p>The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement. Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.</p>\n</blockquote>\n\n<p>The C# 3.0 specification is located at: \n<a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc" rel="nofollow noreferrer">http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc</a></p>\n'}, {'answer_id': 44930, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 0, 'selected': False, 'text': "<p>I suppose there is no fundamental reason why the compiler couldn't automatically translate your switch statement into:</p>\n\n<pre><code>if (t == typeof(int))\n{\n...\n}\nelseif (t == typeof(string))\n{\n...\n}\n...\n</code></pre>\n\n<p>But there isn't much gained by that.</p>\n\n<p>A case statement on integral types allows the compiler to make a number of optimizations:</p>\n\n<ol>\n<li><p>There is no duplication (unless you duplicate case labels, which the compiler detects).  In your example t could match multiple types due to inheritance.  Should the first match be executed? All of them?</p></li>\n<li><p>The compiler can choose to implement a switch statement over an integral type by a jump table to avoid all the comparisons.  If you are switching on an enumeration that has integer values 0 to 100 then it creates an array with 100 pointers in it, one for each switch statement. At runtime it simply looks up the address from the array based on the integer value being switched on.  This makes for much better runtime performance than performing 100 comparisons.</p></li>\n</ol>\n"}, {'answer_id': 44936, 'author': 'fryguybob', 'author_id': 4592, 'author_profile': 'https://Stackoverflow.com/users/4592', 'pm_score': 0, 'selected': False, 'text': '<p>According to <a href="http://msdn.microsoft.com/en-us/library/aa664749(VS.71).aspx" rel="nofollow noreferrer">the switch statement documentation</a> if there is an unambiguous way to implicitly convert the the object to an integral type, then it will be allowed.  I think you are expecting a behavior where for each case statement it would be replaced with <code>if (t == typeof(int))</code>, but that would open a whole can of worms when you get to overload that operator.  The behavior would change when implementation details for the switch statement changed if you wrote your == override incorrectly.  By reducing the comparisons to integral types and string and those things that can be reduced to integral types (and are intended to) they avoid potential issues.</p>\n'}, {'answer_id': 44941, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 3, 'selected': False, 'text': '<p>While on the topic, according to Jeff Atwood, <a href="http://twitter.com/codinghorror/statuses/909900250" rel="noreferrer">the switch statement is a programming atrocity</a>. Use them sparingly. </p>\n\n<p>You can often accomplish the same task using a table. For example:</p>\n\n<pre><code>var table = new Dictionary&lt;Type, string&gt;()\n{\n   { typeof(int), "it\'s an int!" }\n   { typeof(string), "it\'s a string!" }\n};\n\nType someType = typeof(int);\nConsole.WriteLine(table[someType]);\n</code></pre>\n'}, {'answer_id': 44956, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 0, 'selected': False, 'text': '<p>I have virtually no knowledge of C#, but I suspect that either switch was simply taken as it occurs in other languages without thinking about making it more general or the developer decided that extending it was not worth it.</p>\n\n<p>Strictly speaking you are absolutely right that there is no reason to put these restrictions on it. One might suspect that the reason is that for the allowed cases the implementation is very efficient (as suggested by Brian Ensink (<a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44921">44921</a>)), but I doubt the implementation is very efficient (w.r.t. if-statements) if I use integers and some random cases (e.g. 345, -4574 and 1234203). And in any case, what is the harm in allowing it for everything (or at least more) and saying that it is only efficient for specific cases (such as (almost) consecutive numbers).</p>\n\n<p>I can, however, imagine that one might want to exclude types because of reasons such as the one given by lomaxx (<a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44918">44918</a>).</p>\n\n<p>Edit: @Henk (<a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44970">44970</a>): If Strings are maximally shared, strings with equal content will be pointers to the same memory location as well. Then, if you can make sure that the strings used in the cases are stored consecutively in memory, you can very efficiently implement the switch (i.e. with execution in the order of 2 compares, an addition and two jumps).</p>\n'}, {'answer_id': 44970, 'author': 'Henk', 'author_id': 4613, 'author_profile': 'https://Stackoverflow.com/users/4613', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>wrote:</p>\n  \n  <blockquote>\n    <p>"The switch statement does a constant time branch regardless of how many cases you have."</p>\n  </blockquote>\n</blockquote>\n\n<p>Since the language allows the <em>string</em> type to be used in a switch statement I presume the compiler is unable to generate code for a constant time branch implementation for this type and needs to generate an if-then style.</p>\n\n<p>@mweerden - Ah I see. Thanks.</p>\n\n<p>I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The <em>typeof</em> keyword returns an object so this is accessible at run-time only.</p>\n'}, {'answer_id': 45190, 'author': 'BCS', 'author_id': 1343, 'author_profile': 'https://Stackoverflow.com/users/1343', 'pm_score': 0, 'selected': False, 'text': '<p>I think Henk nailed it with the "no sttatic access to the type system" thing</p>\n\n<p>Another option is that there is no order to types where as numerics and strings can be. Thus a type switch would can\'t build a binary search tree, just a linear search.</p>\n'}, {'answer_id': 45240, 'author': 'HS.', 'author_id': 618, 'author_profile': 'https://Stackoverflow.com/users/618', 'pm_score': 0, 'selected': False, 'text': '<p>I agree with <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44941">this comment</a> that using a table driven approach is often better.</p>\n\n<p>In C# 1.0 this was not possible because it didn\'t have generics and anonymous delegates.\nNew versions of C# have the scaffolding to make this work. Having a notation for object literals is also helps.</p>\n'}, {'answer_id': 45584, 'author': 'Ivan Hamilton', 'author_id': 4729, 'author_profile': 'https://Stackoverflow.com/users/4729', 'pm_score': 3, 'selected': False, 'text': '<p>Mostly, those restrictions are in place because of language designers. The underlying justification may be compatibility with languange history, ideals, or simplification of compiler design.</p>\n\n<p>The compiler may (and does) choose to:</p>\n\n<ul>\n<li>create a big if-else statement </li>\n<li>use a MSIL switch instruction (jump table)</li>\n<li>build a Generic.Dictionary&lt;string,int32&gt;, populate it on first use, and call\nGeneric.Dictionary&lt;&gt;::TryGetValue()\nfor a index to pass to a MSIL switch\ninstruction (jump table) </li>\n<li>use a\ncombination of if-elses &amp; MSIL\n"switch" jumps</li>\n</ul>\n\n<p>The switch statement IS NOT a constant time branch. The compiler may find short-cuts (using hash buckets, etc), but more complicated cases will generate more complicated MSIL code with some cases branching out earlier than others. </p>\n\n<p>To handle the String case, the compiler will end up (at some point) using a.Equals(b) (and possibly a.GetHashCode() ). I think it would be trival for the compiler to use any object that satisfies these constraints.</p>\n\n<p>As for the need for static case expressions... some of those optimisations (hashing, caching, etc) would not be available if the case expressions weren\'t deterministic. But we\'ve already seen that sometimes the compiler just picks the simplistic if-else-if-else road anyway...</p>\n\n<p>Edit: <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44918">lomaxx</a> - Your understanding of the "typeof" operator is not correct. The "typeof" operator is used to obtain the System.Type object for a type (nothing to do with its supertypes or interfaces). Checking run-time compatibility of an object with a given type is the "is" operator\'s job. The use of "typeof" here to express an object is irrelevant.</p>\n'}, {'answer_id': 45596, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 3, 'selected': False, 'text': '<p>By the way, VB, having the same underlying architecture, allows much more flexible <code>Select Case</code> statements (the above code would work in VB) and still produces efficient code where this is possible so the argument by techical constraint has to be considered carefully.</p>\n'}, {'answer_id': 45765, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 5, 'selected': False, 'text': '<p>The first reason that comes to mind is <strong>historical</strong>:</p>\n\n<p>Since most C, C++, and Java programmers are not accustomed to having such freedoms, they do not demand them.</p>\n\n<p>Another, more valid, reason is that the <strong>language complexity would increase</strong>:</p>\n\n<p>First of all, should the objects be compared with <code>.Equals()</code> or with the <code>==</code> operator? Both are valid in some cases. Should we introduce new syntax to do this? Should we allow the programmer to introduce their own comparison method?</p>\n\n<p>In addition, allowing to switch on objects would <strong>break underlying assumptions about the switch statement</strong>. There are two rules governing the switch statement that the compiler would not be able to enforce if objects were allowed to be switched on (see the <a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc" rel="noreferrer">C# version 3.0 language specification</a>, §8.7.2):</p>\n\n<ul>\n<li>That the values of switch labels are <em>constant</em></li>\n<li>That the values of switch labels are <em>distinct</em> (so that only one switch block can be selected for a given switch-expression)</li>\n</ul>\n\n<p>Consider this code example in the hypothetical case that non-constant case values were allowed:</p>\n\n<pre><code>void DoIt()\n{\n    String foo = "bar";\n    Switch(foo, foo);\n}\n\nvoid Switch(String val1, String val2)\n{\n    switch ("bar")\n    {\n        // The compiler will not know that val1 and val2 are not distinct\n        case val1:\n            // Is this case block selected?\n            break;\n        case val2:\n            // Or this one?\n            break;\n        case "bar":\n            // Or perhaps this one?\n            break;\n    }\n}\n</code></pre>\n\n<p>What will the code do? What if the case statements are reordered? Indeed, one of the reasons why C# made switch fall-through illegal is that the switch statements could be arbitrarily rearranged.</p>\n\n<p>These rules are in place for a reason - so that the programmer can, by looking at one case block, know for certain the precise condition under which the block is entered. When the aforementioned switch statement grows into 100 lines or more (and it will), such knowledge is invaluable.</p>\n'}, {'answer_id': 48259, 'author': 'Ivan Hamilton', 'author_id': 4729, 'author_profile': 'https://Stackoverflow.com/users/4729', 'pm_score': 7, 'selected': False, 'text': '<p>It\'s important not to confuse the C# switch statement with the CIL switch instruction.</p>\n<p>The CIL switch is a jump table, that requires an index into a set of jump addresses.</p>\n<p>This is only useful if the C# switch\'s cases are adjacent:</p>\n<pre><code>case 3: blah; break;\ncase 4: blah; break;\ncase 5: blah; break;\n</code></pre>\n<p>But of little use if they aren\'t:</p>\n<pre><code>case 10: blah; break;\ncase 200: blah; break;\ncase 3000: blah; break;\n</code></pre>\n<p>(You\'d need a table ~3000 entries in size, with only 3 slots used)</p>\n<p>With non-adjacent expressions, the compiler may start to perform linear if-else-if-else checks.</p>\n<p>With larger non- adjacent expression sets, the compiler may start with a binary tree search, and finally if-else-if-else the last few items.</p>\n<p>With expression sets containing clumps of adjacent items, the compiler may binary tree search, and finally a CIL switch.</p>\n<p>This is full of &quot;mays&quot; &amp; &quot;mights&quot;, and it is dependent on the compiler (may differ with Mono or Rotor).</p>\n<p>I replicated your results on my machine using adjacent cases:</p>\n<blockquote>\n<p>total time to execute a 10 way switch, 10000 iterations (ms): 25.1383\napproximate time per 10 way switch (ms): 0.00251383</p>\n<p>total time to execute a 50 way switch, 10000 iterations (ms): 26.593\napproximate time per 50 way switch (ms): 0.0026593</p>\n<p>total time to execute a 5000 way switch, 10000 iterations (ms): 23.7094\napproximate time per 5000 way switch (ms): 0.00237094</p>\n<p>total time to execute a 50000 way switch, 10000 iterations (ms): 20.0933\napproximate time per 50000 way switch (ms): 0.00200933</p>\n</blockquote>\n<p>Then I also did using non-adjacent case expressions:</p>\n<blockquote>\n<p>total time to execute a 10 way switch, 10000 iterations (ms): 19.6189\napproximate time per 10 way switch (ms): 0.00196189</p>\n<p>total time to execute a 500 way switch, 10000 iterations (ms): 19.1664\napproximate time per 500 way switch (ms): 0.00191664</p>\n<p>total time to execute a 5000 way switch, 10000 iterations (ms): 19.5871\napproximate time per 5000 way switch (ms): 0.00195871</p>\n<p>A non-adjacent 50,000 case switch statement would not compile.\n&quot;An expression is too long or complex to compile near \'ConsoleApplication1.Program.Main(string[])\'</p>\n</blockquote>\n<p>What\'s funny here, is that the binary tree search appears a little (probably not statistically) quicker than the CIL switch instruction.</p>\n<p>Brian, you\'ve used the word &quot;<strong>constant</strong>&quot;, which has a very definite meaning from a computational complexity theory perspective. While the simplistic adjacent integer example may produce CIL that is considered O(1) (constant), a sparse example is O(log n) (logarithmic), clustered examples lie somewhere in between, and small examples are O(n) (linear).</p>\n<p>This doesn\'t even address the String situation, in which a static <code>Generic.Dictionary&lt;string,int32&gt;</code> may be created, and will suffer definite overhead on first use. Performance here will be dependent on the performance of <code>Generic.Dictionary</code>.</p>\n<p>If you check the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf" rel="nofollow noreferrer">C# Language Specification</a> (not the CIL spec)\nyou\'ll find &quot;15.7.2 The switch statement&quot; makes no mention of &quot;constant time&quot; or that the underlying implementation even uses the CIL switch instruction (be very careful of assuming such things).</p>\n<p>At the end of the day, a C# switch against an integer expression on a modern system is a sub-microsecond operation, and not normally worth worrying about.</p>\n<hr />\n<p>Of course these times will depend on machines and conditions. I wouldn’t pay attention to these timing tests, the microsecond durations we’re talking about are dwarfed by any “real” code being run (and you must include some “real code” otherwise the compiler will optimise the branch away), or jitter in the system. My answers are based on using <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx" rel="nofollow noreferrer">IL DASM</a> to examine the CIL created by the C# compiler. Of course, this isn’t final, as the actual instructions the CPU runs are then created by the JIT.</p>\n<p>I have checked the final CPU instructions actually executed on my x86 machine, and can confirm a simple adjacent set switch doing something like:</p>\n<pre><code>  jmp     ds:300025F0[eax*4]\n</code></pre>\n<p>Where a binary tree search is full of:</p>\n<pre><code>  cmp     ebx, 79Eh\n  jg      3000352B\n  cmp     ebx, 654h\n  jg      300032BB\n  …\n  cmp     ebx, 0F82h\n  jz      30005EEE\n</code></pre>\n'}, {'answer_id': 952967, 'author': 'Roman Starkov', 'author_id': 33080, 'author_profile': 'https://Stackoverflow.com/users/33080', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>I don\'t see any reason why the switch statement has to succomb to static analysis only</p>\n</blockquote>\n\n<p>True, it doesn\'t <em>have</em> to, and many languages do in fact use dynamic switch statements. This means however that reordering the "case" clauses can change the behaviour of the code.</p>\n\n<p>There\'s some interesting info behind the design decisions that went into "switch" in here: <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336815.aspx" rel="noreferrer">Why is the C# switch statement designed to not allow fall-through, but still require a break?</a></p>\n\n<p>Allowing dynamic case expressions can lead to monstrosities such as this PHP code:</p>\n\n<pre><code>switch (true) {\n    case a == 5:\n        ...\n        break;\n    case b == 10:\n        ...\n        break;\n}\n</code></pre>\n\n<p>which frankly should just use the <code>if-else</code> statement.</p>\n'}, {'answer_id': 2396963, 'author': 'Dave Swersky', 'author_id': 34796, 'author_profile': 'https://Stackoverflow.com/users/34796', 'pm_score': 2, 'selected': False, 'text': '<p>Judah\'s answer above gave me an idea.  You can "fake" the OP\'s switch behavior above using a <code>Dictionary&lt;Type, Func&lt;T&gt;</code>:</p>\n\n<pre><code>Dictionary&lt;Type, Func&lt;object, string,  string&gt;&gt; typeTable = new Dictionary&lt;Type, Func&lt;object, string, string&gt;&gt;();\ntypeTable.Add(typeof(int), (o, s) =&gt;\n                    {\n                        return string.Format("{0}: {1}", s, o.ToString());\n                    });\n</code></pre>\n\n<p>This allows you to associate behavior with a type in the same style as the switch statement.  I believe it has the added benefit of being keyed instead of a switch-style jump table when compiled to IL.</p>\n'}, {'answer_id': 42305628, 'author': 'dimaaan', 'author_id': 1802286, 'author_profile': 'https://Stackoverflow.com/users/1802286', 'pm_score': 3, 'selected': False, 'text': '<p>Microsoft finally heard you!</p>\n\n<p>Now with C# 7 you can:</p>\n\n<pre><code>switch(shape)\n{\ncase Circle c:\n    WriteLine($"circle with radius {c.Radius}");\n    break;\ncase Rectangle s when (s.Length == s.Height):\n    WriteLine($"{s.Length} x {s.Height} square");\n    break;\ncase Rectangle r:\n    WriteLine($"{r.Length} x {r.Height} rectangle");\n    break;\ndefault:\n    WriteLine("&lt;unknown shape&gt;");\n    break;\ncase null:\n    throw new ArgumentNullException(nameof(shape));\n}\n</code></pre>\n'}, {'answer_id': 60015525, 'author': 'smolchanovsky', 'author_id': 10433685, 'author_profile': 'https://Stackoverflow.com/users/10433685', 'pm_score': 0, 'selected': False, 'text': '<p>C# 8 allows you to solve this problem elegantly and compactly using an switch expression:</p>\n\n<pre><code>public string GetTypeName(object obj)\n{\n    return obj switch\n    {\n        int i =&gt; "Int32",\n        string s =&gt; "String",\n        { } =&gt; "Unknown",\n        _ =&gt; throw new ArgumentNullException(nameof(obj))\n    };\n}\n</code></pre>\n\n<p>As a result, you get:</p>\n\n<pre><code>Console.WriteLine(GetTypeName(obj: 1));           // Int32\nConsole.WriteLine(GetTypeName(obj: "string"));    // String\nConsole.WriteLine(GetTypeName(obj: 1.2));         // Unknown\nConsole.WriteLine(GetTypeName(obj: null));        // System.ArgumentNullException\n</code></pre>\n\n<p>You can read more about the new feature <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions" rel="nofollow noreferrer">here</a>.</p>\n'}]
['https://Stackoverflow.com/questions/44905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394/']