A base class reference can refer to a derived class object : Derived Class « Class « C# / CSharp Tutorial






using System; 
 
class BaseClass { 
  public int a; 
 
  public BaseClass(int i) { 
    a = i; 
  } 
} 
 
class DerivedClass : BaseClass { 
  public int b; 
 
  public DerivedClass(int i, int j) : base(j) { 
    b = i; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    BaseClass x = new BaseClass(10); 
    BaseClass x2;  
    DerivedClass y = new DerivedClass(5, 6); 
 
    x2 = x; // OK, both of same type 
    Console.WriteLine("x2.a: " + x2.a); 
 
    x2 = y; // Ok because DerivedClass is derived from BaseClass 
    Console.WriteLine("x2.a: " + x2.a); 
 
    // BaseClass references know only about BaseClass members 
    x2.a = 19; // OK 
//    x2.b = 27; // Error, BaseClass doesn't have a b member 
  } 
}
x2.a: 10
x2.a: 6








7.21.Derived Class
7.21.1.A base class reference can refer to a derived class object
7.21.2.Illustrates member hiding
7.21.3.Illustrates member accessibility in subclass
7.21.4.base and derived classes