A new() constructor constraint

image_pdfimage_print
   


using System;

class MyClass {

  public MyClass() {
  }

}

class Test<T> where T : new() {
  T obj;

  public Test() {
    // This works because of the new() constraint.
    obj = new T(); // create a T object
  }
}

class ConsConstraintDemo {
  public static void Main() {

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

  }
}
           
          


This entry was posted in Generics. Bookmark the permalink.