Milk Biscuit
Milk Biscuit

Reputation: 28

Is it possible to find a given child class in a list of parent classes in C#?

Given a list of ClassA, populated by several child classes of ClassA (Like ClassB, or ClassC), is there a way to iterate through the list and find instances of ClassB or ClassC and access their class-exclusive methods?

Upvotes: 0

Views: 59

Answers (2)

r_c
r_c

Reputation: 176

Sure, it is. The usual pattern for the code is

 ClassB classB = classA as ClassB;
 if (classB == null)
 {
     // do something else, probably return
 }
 classB.DoTheThingYouNeedClassBFor();

Though, as an aside, this situation is a bit of a "code smell". Usually, if you find yourself in that situation, there is room for improvement in your design. If you elaborate on the problem you are trying to solve, perhaps someone can suggest a better solution.

Upvotes: 1

xanth
xanth

Reputation: 172

Assuming that you have a list of some non homogeneous classes you can do something like this:

void Main()
{
    var a = new List<A>{
        new A(),
        new B(),
        new C()
    };

    //1
    Console.Write(a.Where(x => x is C).ToList().Count());
}

public class A {
    string a;
}

public class B: A {
    int b;
}

public class C: B {
    long c;
}

Upvotes: 1

Related Questions