0

Why can't I cast a base class to a derived class? Also, why doesn't the compiler catch this?

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Parent p = new Parent();
            Child c = (Child)p;

        }
    }

    class Parent
    {
        public string Data { get; set; }
    }

    class Child : Parent
    {
        public string OtherDate { get; set; }
    }
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49

1 Answers1

0

p is an instance of Parent, so you cannot tell the runtime to interpret it as one.

The compiler does not catch it because code like this

 Parent p = new Child();
 Child c = (Child)p;

and compilers do not do the static code analysis needed to catch it. Reasons for not checking it are:

  • It is time consuming

  • It can only catch some of the instances of the error.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
SJuan76
  • 24,532
  • 6
  • 47
  • 87