tags:

views:

70

answers:

4

I'm trying to avoid using a long else if statement.

Lets say I have an object and I want to test if it's of type ClassA, ClassB, ClassC, etc..?

What is a clean way of doing this?

A: 

myobject.GetType() will yield the objects type to test for equality against other types.

Pierreten
+2  A: 

have a list of types you want to test against then ask the list if it "Contains" the type of object you have?

Also, not sure why you are doing that.

But perhaps something like IsAssignableFrom ( http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx ) is what you are looking for?

Keith Nicholas
+3  A: 

Something like..

if (new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) }.Contains(obj.GetType()))

?

And obviously if you have a lot of types and are seeing bad performance, then throw it into a dictionary and use ContainsKey.

Scott Bilas
Exactly what I was looking for. Thanks
jdelator
+5  A: 

Often, when you have to test an object's type, it can be a sign that there's something wrong with your design. Object oriented programming offers us an opportunity to avoid these sorts of constructs via polymorphism.

Wouldn't it be better if A,B and C implemented the bodies of your proposed if statements under a base class interface such that you don't have to test upstream?

For instance:

abstract class A
{
    public virtual void SomeBehavior()
    {
        Console.WriteLine("default behavior");
    }
}

class B:A
{
    public override void SomeBehavior()
    {
         Console.WriteLine("type specific behavior");
    }
}

class C:A
{
    public override void SomeBehavior()
    {
         Console.WriteLine("different behavior");
    }
}

class D:A{}

void Main()
{
    IEnumerable<A> myCollection=new A[]{new B(),new C(),new D()};
    foreach(A item in myCollection)
    {
        item.SomeBehavior();
    }
}
spender
I can't modify class a, b or c but this will work very nicely for anyone that can.
jdelator