You cannot assign a base class instance to a derived class variable unless
the instance is the derived type.
A derived type is a superset of the base type. If you try to assign the only
the base type (which is a subset of the derived type) to a superset
variable, then you'll get an error. Suppose you had a base class called
Person (Name, Age etc.) and a derived class called Employee (All of Person,
Employee No etc.). If you only create a person object, no space has been
allocated for the extra stuff needed by an Employee class, so you cannot
assign
For example:
Assume MyClassB inherits from MyClassA
The following will work:
MyClassB myVariableB = New MyClassB();
MyClassA myVariableA = (MyClassA) myVariableB;
The following is won't work:
MyClassA myVariableA = New MyClassA();
MyClassB myVariableB = (MyClassB) myVariableA;
The following will work because myVariableA is actually of type MyClassB:
MyClassA myVariableA = (MyClassA) New MyClassB();
MyClassB myVariableB = (MyClassB) myVariableA;
Sorry for sounding more complicated than this is. Someone else can hopefully
provide a better explanation of how inheritance works.
For your code to work, you'd need to do something like:
public class B : A
{
public B: base()
{}
static void main()
{
B derived = (B) new B();
}
}
Hope this helps,
Trev.