Instantiate a generic type in a C # class

Pretty simple question in C #,

class Data<T> { T obj; public Data() { // Allocate to obj from T here // Some Activator.CreateInstance() method ? obj = ??? } } 

How can I do it?

+7
generics instantiation c #
source share
3 answers

If you want to create your own instance of T, you need to define a new() constraint

 class Data<T> where T: new() { T obj; public Data() { obj = new T(); } } 

If you want to pass an obj object, you need to enable it in the constructor

  class Data<T> { T obj; public Data(T val) { obj = val; } } 
+20
source share

You can use the new constraint in your generic class definition to ensure that T has a default constructor that you can call. Constraints allow the compiler to be informed of certain types of behavior (capabilities) that the general parameter T must adhere to.

 class Data<T> where T : new() { T obj; public Data() { obj = new T(); } } 
0
source share
0
source share

All Articles