1

In C#, in a switch statement non constant values are not allowed in a case label. If you need to support non constant values then you have to use an if statement.

My question is rather simple: Is switch internally implemented in such a way that restricting to constant values allows some kind of optimization that otherwise couldn't be done? What I'm basically asking is if these two code snippets would perform exactly the same:

switch (myEnumVariable) { case MyEnum.Value1: .... break; case MyEnum.Value2: ..... .... default: .... } if (myEnumVariable == MyEnum.Type1) { .... } else if (myEnumVariable == MyEnum.Type2) { .... } ... else { .... } 

Or does the switch statement have an advantage due to it's restriction. If not, why have the restriction?

2
  • Honestly, I'm quite confident that the JIT compiler's optimizations will do the best. I'd guess that profiling the two codes won't show any difference. Or at least, not any signifiant difference. Commented Sep 25, 2014 at 16:11
  • @SteveB And your guess would be wrong, as the implementations can be radically different, both in performance and also in possible semantics. Commented Sep 25, 2014 at 16:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.