3
votes

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.

5
There is no way the cast would throw if the objects really derive from Parent. Check your assumptions.Jon
Show your implementation of Child1 and Parent, I guess parent is a property of Child1. Parent p = ((Child1)child).Parent?Peter

5 Answers

4
votes

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>())
{

}
1
votes

Use List<Parent> instead of List<object>

1
votes

You can cast it by using Linq

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

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.

1
votes

You can use dynamic type when you enumerate your list:

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