Overriding Virtual Methods in a Generic Class


A virtual method in a generic class can be overridden just like any other method. For example, consider this program in which the virtual method getob( ) is overridden:

 // Overriding a virtual method in a generic class. using System; // A generic base class. class Gen<T> {   protected T ob;   public Gen(T o) {     ob = o;   }   // Return ob. This method is virtual.   public virtual T getob() {     Console.Write("Gen's getob(): " );     return ob;   } } // A derived class of Gen that overrides getob(). class Gen2<T> : Gen<T> {   public Gen2(T o) : base(o) {  }   // Override getob().   public override T getob() {     Console.Write("Gen2's getob(): ");     return ob;   } } // Demonstrate generic method override. class OverrideDemo {   public static void Main() {     // Create a Gen object for int.     Gen<int> iOb = new Gen<int>(88);     // This calls Gen's version of getob().     Console.WriteLine(iOb.getob());     // Now, create a Gen2 object and assign its     // reference to iOb (which is a Gen<int> variable).     iOb = new Gen2<int>(99);     // This calls Gen2's version of getob().     Console.WriteLine(iOb.getob());   } }

The output is shown here:

 Gen's getob(): 88 Gen2's getob(): 99

As the output confirms, the overridden version of getob( ) is called for an object of type Gen2, but the base class version is called for an object of type Gen.

Notice one other point. This line:

 iOb = new Gen2<int>(99);

is valid because iOb is a variable of type Gen<int>. Thus, it can refer to any object of type Gen<int>, or any object of a class derived from Gen<int>, including Gen2<int>. Of course, iOb couldn’t be used to refer to an object of type Gen2<double>, for example, because of the type mismatch.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net