4 ms·
I can't say I agree in any way. There's no instance where a switch statement is preferable to a hash table or pattern matching. If you have a switch with 3 or
by debacle 10y ago
I can't say I agree in any way. There's no instance where a switch statement is preferable to a hash table or pattern matching.
If you have a switch with 3 or fewer cases, use if/else. If you have a switch with more cases, a hash table is going to wind up with far less code, and set you up for polymorphism later if you decide you need to go that route.
- svick 10y agoHow do you create a hash table where the value is an action that depends on the type of the value? The best you can do is something like Dictionary<Type, Action<object>> and use casting in the action, but that's much worse than C# 7.0 switch.
- barrkel 10y agoIn the context of the article (C# patterns), I'm talking about switch statements specifically as a kind of pattern matching. I disagree that hash tables will end up with less code; the dispatch mechanism for a hash table will be significantly longer than a switch, and the compiler can create a hash table for dispatch (using e.g. a perfect hash function). A switch statement will both be faster and easier to understand and read than storing lambdas in a hash table. For pure readability, languages with good support for hash literals and lambdas may have the edge, but they'll also encourage dynamism that will hurt both simplicity and performance.