I have two classes
public class A
{
public A()
{
}
}
public class B:A
{
public B()
{
}
}
and it the code in Main is as follows
A oa = new B();
B ob = new A();
Here line 1 compiles successfully while line 2 displays typecasting error. Why this happens. What exactly happens when new B() and new A() gets called?
new A()constructs an object of typeAon the heap and returns a reference to it.new B()constructs an object of typeBon the heap and returns a reference to it.Since
BsubclassesA, it is valid for a reference of typeAto refer to an object of run-time typeB. After all,Bis simply a “special case” ofA.However, the converse is not true, because not all
As can be consideredBs.Although this is strictly enforced by C#’s safe type-system even if there is no “real” incompatibility, the reasons for such restrictions are natural. Imagine, for example, that
Bdeclared a propertypublic int Foo {get; set;}.How would you expect this to behave:
This is clearly illogical: the real object that the reference is referring to has no such property. Consequently, the compiler prohibits such constructs.
Now imagine you changed your code to:
B b = (B)new A();Here, you are telling the compiler that the object created, will, at run-time, be assignable to a reference of type
B. This will compile fine, but since the assertion is clearly incorrect, a run-timeInvalidCastExceptionwill be thrown.To summarize, C#’s type system (if you ignore
dynamicand a few special cases) is both static and safe: you will not successfully be able to treat a concrete instance ofAas though it were of typeB.