C Switch On Type
Possible Duplicate:
C# - Is there a better alternative than this to 'switch on type'?
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. The syntax for a switch statement in C programming language is as follows −. Dec 24, 2010 Sure. You need to come up with some way to query the information if you're stuck in C03, or use auto in C11 and up. So long as you don't try to return different types within the same instantiation you'll have no problem.
C# doesn't support switching on the type of an object. What is the best pattern of simulating this:
Thanks!
marked as duplicate by ChrisF♦, Michael Myers♦Sep 26 '12 at 16:25
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
5 Answers
I usually use a dictionary of types and delegates.
It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.
NoctisThere is a simple answer to this question at Switch case on type c# which use a dictionary of types to look-up a lambda function.
Here is how it might be used
C Switch Data Type
There is also a generalized solution to this problem in terms of pattern matching (both types and run-time checked conditions) at switch / pattern matching idea
Update:This got fixed in C# 7.0 with pattern matching
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 know about.
Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx
Otherwise something along these lines could help
etc.
gjvdkampgjvdkampI did it one time with a workaround, hope it helps.
Ghyath SerhalGhyath SerhalC# 8 Switch
I have used this form of switch-case
on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.
If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.
Here is a little example expanding on Mark's solution. I think it is a great way to work with types:
IAbstractIAbstract