Demonstrate a reference constraint

image_pdfimage_print
   


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>();
  }
}
           
          


This entry was posted in Generics. Bookmark the permalink.