AbyssWalker
AbyssWalker

Reputation: 43

In c# how do you compare a child type with the reference of its parent?

In details, I have list of multiple child classes with the reference of its parent class. like -->

List<Parent> p = new List<Parent>();
Parent c1 = new Child1();
Parent c2 = new Child2();
p.Add(c1);
p.Add(c2);

So, when I iterate through the p list, how can I compare if the object in the list is from one specific child class. Like I want to compare if,

p[i] == Child1, then do stuff//

Upvotes: 1

Views: 945

Answers (2)

Maximilian Ast
Maximilian Ast

Reputation: 3499

You can use pattern matching in C#7 in switch statement for that:

switch(p[i])
{
    case Child1 child1:
        /* ... */
        Console.WriteLine(child1.propert1);
        break;
    case Child2 child1:
        /* ... */
        Console.WriteLine(child2.propert2);
        break;
    default:
        /* ... */
        Console.WriteLine("No known child!");
        break;
}

Upvotes: 3

Rudi Visser
Rudi Visser

Reputation: 21989

You can check if p[i] is of a specific type by using is, for example:

if (p[i] is Child1) {
   // Do something
}

If you need to operate on the object, you can get a reference back to the object in addition as its type using is (thanks to @Jonathan Barclay), and could change your code to:

if (p[i] is Child1 c1) {
   // Do something with c1
}

Upvotes: 4

Related Questions