Demonstrate a value type constraint

image_pdfimage_print
   


using System;

struct MyStruct {
}

class MyClass {
}

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

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

class Test {
  public static void Main() {
    Test<MyStruct> x = new Test<MyStruct>(new MyStruct());
    Test<int> y = new Test<int>(10);

    // But, the following declaration is illegal!
//    Test<MyClass> z = new Test<MyClass>(new MyClass());
  }
}
           
          


This entry was posted in Generics. Bookmark the permalink.