Using Case/Switch and GetType to determine the object


Possible Duplicate:
C# - Is there a better alternative than this to ‘switch on type’?

If you want to switch on a type of object, what is the best way to do this?

Code snippet

private int GetNodeType(NodeDTO node)
    switch (node.GetType())
        case typeof(CasusNodeDTO):
            return 1;
        case typeof(BucketNodeDTO):
            return 3;
        case typeof(BranchNodeDTO):
            return 0;
        case typeof(LeafNodeDTO):
            return 2;
            return -1;

I know this doesn't work that way, but I was wondering how you could solve this. Is an if/else statement appropriate in this case?

Or do you use the switch and add .ToString() to the type?

5/23/2017 11:47:26 AM

Accepted Answer

If I really had to switch on type of object, I'd use .ToString(). However, I would avoid it at all costs: IDictionary<Type, int> will do much better, visitor might be an overkill but otherwise it is still a perfectly fine solution.

4/2/2009 9:10:32 AM

This won't directly solve your problem as you want to switch on your own user-defined types, but for the benefit of others who only want to switch on built-in types, you can use the TypeCode enumeration:

switch (Type.GetTypeCode(node.GetType()))
    case TypeCode.Decimal:
        // Handle Decimal

    case TypeCode.Int32:
        // Handle Int32

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow