Methodology for Switch based on an object
-
I am learning C#, coming from VB.NET I would like to know what method is commonly used to make a decision based on the contents of an object. For something like: if ( obj is MyType1 ) ... else if ( obj is MyType2 ) ... else if ( obj is MyType3 ) ... could be quite lengthy. Naively: switch( obj ) { case MyType1: ... Case MyType2: ... Case MyType3: ... } This, I realise is incorrect because switch only accepts integral types or strings. Is there another way of doing it? Any help appreciated, Shayne
-
I am learning C#, coming from VB.NET I would like to know what method is commonly used to make a decision based on the contents of an object. For something like: if ( obj is MyType1 ) ... else if ( obj is MyType2 ) ... else if ( obj is MyType3 ) ... could be quite lengthy. Naively: switch( obj ) { case MyType1: ... Case MyType2: ... Case MyType3: ... } This, I realise is incorrect because switch only accepts integral types or strings. Is there another way of doing it? Any help appreciated, Shayne
-
Try
string temp = Object.GetType().ToString(); switch(temp) { case "typeA": break; case "typeB": break; default: break; }
Kev Pearman MCPOr, the best way is to use visitor pattern (http://www.dofactory.com/Patterns/PatternVisitor.aspx), especially if you cast your objects after doing "is". if (obj is MyType) { objOfMyType = (MyType)obj; ... } The visitor pattern will get rid of casts, and allow you to create new classes and not having to add if (obj is MyNewType) or case statements.