A base class constraint : Generic Constraint : Generics C# Source Code


Custom Search

C# Source Code » Generics » Generic Constraint »

 

A base class constraint









    


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!
  }
}


           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Generics
» Generic Constraint