Search code examples
c#.net.net-2.0runtime

Efficient run-time type checking


I have hierarchy of classes like follows (in fact I have more than 3 derived types):

class A {};
class B : A  {};
class C : B  {};
class D : A  {};

Instances of these classes are stored in List<A> collections. Sometimes collections are quite big (thousands or even tens of thousands of objects).

In my code I frequently need to perform some actions depending on the exact type of the objects. Something like this:

List<A> collection = ...
foreach (A obj in collection)
{
    if (obj is C)
        something(obj as C);
    else if (obj is B)
        somethingElse(obj as B);
    ....
}

As you see, the code performs many checks for type of the object and casts. For collections with many elements performance of the code is not that great.

What would you recommend to speed up run time type checks in my case?


Solution

  • It sounds to me like you should move the "something" into a virtual method on A, then each of B, C and D can override it as they need (which may just mean calling an external method - they don't need to do the work themselves) - or not override as they need.

    Then this becomes:

    foreach (A obj in collection)
    {
        obj.DoSomething();
    }
    

    i.e.

    class A {
        public virtual void DoSomething() {...}
    }
    class B : A   {
        public override void DoSomething() {...}
    }
    

    etc