I was trying to cast my parent into my child (aka Down casting). Below is the example for the same:
public class Parent
{
public void ParentMethod()
{
Console.WriteLine("In Parent Method");
}
}
public class Child : Parent
{
public void ParentMethod()
{
Console.WriteLine("In Child Method");
}
}
I get no compile time error, however when I execute my below code, I get the exception like this Unable to cast object of type 'Parent' to type 'Child'.
Child obj2 = (Child)new Parent();
obj2.ParentMethod();
Please help me in getting the below questions answer:
- How to resolve this exception.
- Is this is a good way to explain Up/Down casting.
- Which ParentMethod will be called by complier, in this example i.e. of Parent class or of Child class.