A base class constraint

image_pdfimage_print


   


using System;

class MyBase {
  public void hello() {
    Console.WriteLine("Hello");
  }
}

class B : MyBase { }

class C { }

class Test<T> where T : MyBase {
  T obj;

  public Test(T o) {
    obj = o;
  }

  public void sayHello() {
    obj.hello();
  }
}

class BaseClassConstraintDemo {
  public static void Main() {
    MyBase a = new MyBase();
    B b = new B();
    C c = new C();

    Test<MyBase> t1 = new Test<MyBase>(a);

    t1.sayHello();

    Test<B> t2 = new Test<B>(b);

    t2.sayHello();

    // The following is invalid because
    // C does not inherit MyBase.
    // Test<C> t3 = new Test<C>(c); // Error!
  }
}


           
          


This entry was posted in Generics. Bookmark the permalink.