-2
ClassA
{

}

ClassB : ClassA
{

}

I can do

ClassA objA = new ClassB();

but why I can't do reverse

ClassB objB = new ClassA();

What exactly happens in back end?How compiler treat this?

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
Sanky V
  • 1
  • 3
  • 3
    Did you mean to put some inheritance in here? I answered this on the basis that `ClassA` was the base class, but omitted to read your question carefully enough. – Bathsheba Mar 20 '17 at 09:24
  • Without inheritance: `ClassA objA = new ClassB();` will also not work. – wake-0 Mar 20 '17 at 09:25
  • You forgot to inherit something or? Current code won't compile, nor *"I can do"* part will work. – Sinatr Mar 20 '17 at 09:25
  • Possible duplicate of [Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?](http://stackoverflow.com/questions/729527/is-it-possible-to-assign-a-base-class-object-to-a-derived-class-reference-with-a) – Sinatr Mar 20 '17 at 09:30

1 Answers1

0

Because the compiler automatically casts the deriving class to the base class - it just interprets it as an object of the base class, ignoring other properties. But to cast an object to the derived class, it must have been an object of this derived class before and the compiler wants you to explicitly define the cast. But even if you'd define the cast explicitly, it wouldn't work because the object has never been of the derived type.

MetaColon
  • 2,895
  • 3
  • 16
  • 38