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?
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?
myobject.GetType() will yield the objects type to test for equality against other types.
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?
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.
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();
}
}