Demonstrate a reference constraint : Generic Constraint : Generics C# Source Code


Custom Search

C# Source Code » Generics » Generic Constraint »

 

Demonstrate a reference constraint








    


using System;
class MyClass {
}

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

  public Test() {
    // The following statement is legal only
    // because T is guaranteed to be a reference
    // type, which can be assigned the value null.
    obj = null;
  }
  public void print(){
     Console.WriteLine(obj);
  }
}

class ClassConstraintDemo {
  public static void Main() {

    Test<MyClass> x = new Test<MyClass>();

    // The next line is in error because int is
    // a value type.
//    Test<int> y = new Test<int>();
  }
}
           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Generics
» Generic Constraint