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.
Parent
. Check your assumptions. – Jon