Mhdali
Mhdali

Reputation: 688

Casting Child object stored as List<object> to Parent object

I have a Parent class, and bunch of child classes (Child1, Child2, Child3) that all inhirits from Parent class.

I store different objects from child classes in an object list (List), I need to check some properties inhirited from Parent class in these child objects, I tried to cast the child objects to Parent class, but I get invalid cast exception.

Child1 aChild1 = new Child1();
Child2 aChild2 = new child2();

List<object> childsList = new List<object>();

childsList.Add(aChild1);
childsList.Add(aChild2);

foreach(object child in childsList)
{
    Parent p = (Parent)child;//Here I got the exception
}

I can check the type of the child object using 'is'.

if (child is Child1){}
else if (child is Child2{} .....

or by getting child's type and comparing it to the class names to know the type:

if (child.GetType().Name.Equals("Child1")
     //Do whatever
else if (child.GetType().Name.Equals("Child2")
     //Do another whatever :D

But I'm searching for a better method to cast the childs to their parent class.

Upvotes: 3

Views: 3525

Answers (5)

Chris Sinclair
Chris Sinclair

Reputation: 23198

Given your comment "The problem is I use the same list to store objects that are not childs of Parent.", this list contains a mix of Parent objects and other unrelated objects.

Then you'll have to filter them out in a graceful manner. The easiest is probably with LINQ's OfType method:

List<Parent> result = childsList.OfType<Parent>().ToList();

Any objects which aren't a Parent will be ignored.

That said, this is (typically) a significant code smell and a more ideal situation would be that you don't mix the objects stored in your listing, so the childsList can be strongly typed as a List<Parent> in the first place, but it's hard to comment with specifics for a "better method" without knowing the rest of your application design.

EDIT: Here's its use with your existing code:

foreach(Parent p in childsList.OfType<Parent>())
{

}

Upvotes: 4

Alex Scherbinin
Alex Scherbinin

Reputation: 43

You can use dynamic type when you enumerate your list:

foreach(dynamic child in childsList)
{
    child.ParentPropertyName; // here you can check Parent property value
}

Upvotes: 1

Tigran
Tigran

Reputation: 62248

I need to check some properties inhirited from Parent class in these child objects

If properties are inherited there is no need to cast, there should be already visible on child level.

By the way, if you cast and get an exception, that means that type does not relly inherit base class.

Upvotes: 1

petchirajan
petchirajan

Reputation: 4352

You can cast it by using Linq

IEnumerable<Parent> result = childsList.Cast<Parent>().ToList();

Upvotes: 1

Dmitriy Finozhenok
Dmitriy Finozhenok

Reputation: 854

Use List<Parent> instead of List<object>

Upvotes: 1

Related Questions