C# switch on type
c#, switch-statement, typeof
Solution
See another answer; this feature now exists in C#
I usually use a dictionary of types and delegates.
var @switch = new Dictionary<Type, Action> {
{ typeof(Type1), () => ... },
{ typeof(Type2), () => ... },
{ typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();
It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.
Problem
Possible Duplicate: C# - Is there a better alternative than this to 'switch on type'? C# doesn't support switching on the type of an object. What is the best pattern of simulating this: ``` switch (typeof(MyObj)) case Type1: case Type2: case Type3: ```
Related problems
- How to use switch-case on a Type?
- Switch case on type c#
- Is there a better alternative than this to 'switch on type'?
- What is quicker, switch on string or elseif on type?
- Is it possible to use an nameof expression in switch statement?
- C#: Call non-generic method from generic method
- C# switch statement limitations - why?
- Is there any benefit to this switch / pattern matching idea?