Pretty basic question in C#,
class Data<T>
{
T obj;
public Data()
{
// Allocate to obj from T here
// Some Activator.CreateInstance() method ?
obj = ???
}
}
How do i do this?
YOU can use the new
constraint in your generic class definition to ensure T has a default constructor you can call. Constraints allow you to inform the compiler about certain behaviors (capabilities) that the generic parameter T must adhere to.
class Data<T> where T : new()
{
T obj;
public Data()
{
obj = new T();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With