Hi all,
I whonder how can I manage an object subtype.
Explain: take a (pseudocode) sub like the following
void DoSomething(object o)
{
switch (o.type)
{
case string
...
case int32
....
}
}
How can I translate in working c#?
Thanx!
Printable View
Hi all,
I whonder how can I manage an object subtype.
Explain: take a (pseudocode) sub like the following
void DoSomething(object o)
{
switch (o.type)
{
case string
...
case int32
....
}
}
How can I translate in working c#?
Thanx!
That should almost work:
PHP Code:switch ( o.GetType().ToString() )
{
case "System.String"
break;
case "System.Int32"
break;
default:
//error
break;
}
Yes, I thinked at this, but I don't like string comparison for such a case. :(Quote:
Originally posted by Scott Penner
That should almost work:
PHP Code:switch ( o.GetType().ToString() )
{
case "System.String"
...
}
sometime ago i though of the same and the only thing that really worked was with strings
Now I thiked this:Quote:
Originally posted by PT Exorcist
sometime ago i though of the same and the only thing that really worked was with strings
switch (true)
{
case myObject.GetType.Equals("a".GetType)
... is a string
...
}
But I don't like this too much
I like your last idea, of not using the "ToString" method. How did direct comparison of the "ToType" methods work out for you?
Yeah, but the last example doesn't work in c#.
The case statement must only have constants.
The best way to do this will be with an if/then/else loop.
Then you can compare types directly. If you are working with a large number of types, you could create an array of the types to compare against, then loop through these to perform the comparison.
For instance, you could have an array consisting of a class that holds two properties, an enumeration value and a class type. Once the comparison returns true, you store the corresponding enumeration value. You can then use this enumeration value in your case statement and go from there.