0

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:

  1. How to resolve this exception.
  2. Is this is a good way to explain Up/Down casting.
  3. Which ParentMethod will be called by complier, in this example i.e. of Parent class or of Child class.
HarshSharma
  • 630
  • 3
  • 9
  • 34
  • See duplicate, especially: _"subclasses provide more than base classes - where does this "more" come from?"_ – CodeCaster Feb 25 '16 at 20:09
  • 1
    An instance of `Parent` isn't an instance of `Child`. This is like saying `string s = (string)new object();` – Lee Feb 25 '16 at 20:09
  • @Lee or like saying `var animal = new Animal(); var dog = (Dog)animal;`. You cannot solve this problem by casting alone. – CodeCaster Feb 25 '16 at 20:10

0 Answers0