C# switch on type [duplicate]

Update: This got fixed in C# 7.0 with pattern matching switch (MyObj) case Type1 t1: case Type2 t2: case Type3 t3: Old answer: It is a hole in C#’s game, no silver bullet yet. You should google on the ‘visitor pattern’ but it might be a little heavy for you but still something you should … Read more

Is there any significant difference between using if/else and switch-case in C#?

SWITCH statement only produces same assembly as IFs in debug or compatibility mode. In release, it will be compiled into jump table (through MSIL ‘switch’ statement)- which is O(1). C# (unlike many other languages) also allows to switch on string constants – and this works a bit differently. It’s obviously not practical to build jump … Read more

How to use null in switch

This is was not possible with a switch statement in Java until Java 18. You had to check for null before the switch. But now, with pattern matching, this is a thing of the past. Have a look at JEP 420: Pattern matching and null Traditionally, switch statements and expressions throw NullPointerException if the selector … Read more

Why does Java switch on contiguous ints appear to run faster with added cases?

As pointed out by the other answer, because the case values are contiguous (as opposed to sparse), the generated bytecode for your various tests uses a switch table (bytecode instruction tableswitch). However, once the JIT starts its job and compiles the bytecode into assembly, the tableswitch instruction does not always result in an array of … Read more