Overriding a virtual method in a generic class : Generic Class Hierarchy « Generics « C# / C Sharp






Overriding a virtual method in a generic class

Overriding a virtual method in a generic class

using System;

class MyBaseGenericClass<T> {
  protected T myObject;

  public MyBaseGenericClass(T o) {
    myObject = o;
  }

  public virtual T getmyObject() {
    Console.Write("Base's getmyObject(): " );
    return myObject;
  }
}

class MyGenericClass<T> : MyBaseGenericClass<T> {

  public MyGenericClass(T o) : base(o) {  }

  public override T getmyObject() {
    Console.Write("overide getmyObject(): ");
    return myObject;
  }
}

class Test {
  public static void Main() {
    MyBaseGenericClass<int> myObject = new MyBaseGenericClass<int>(8);

    Console.WriteLine(myObject.getmyObject());

    myObject = new MyGenericClass<int>(9);

    Console.WriteLine(myObject.getmyObject());
  }
}
           
       








Related examples in the same category

1.A simple generic class hierarchyA simple generic class hierarchy
2.A derived class with its own type parametersA derived class with its own type parameters
3.A non-generic class can be the base class of a generic derived classA non-generic class can be the base class of a generic derived class
4.The overriding method cannot change the inherited constraints.