Demonstrate a value type constraint : Generic Constraint : Generics C# Source Code


Custom Search

C# Source Code » Generics » Generic Constraint »

 

Demonstrate a value type constraint








    


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







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Generics
» Generic Constraint