Possible Duplicate:
What does new() mean?
Like in title. I wonder what this syntax in the code means. I've find it in some samples but it wasn't explained and I don't really know what it does.
public class SomeClass<T> where T: new() // what does it mean?
Can anyone explain that for me?
Perhaps you mean you saw something along these lines?
public class SomeClass<T> where T: new()
{...}
which means that you can only use the generic class with a type T that has a public parameterless constructor. These are called generic type constraints. I.e., you cannot do this (see CS0310):
// causes CS0310 because XmlWriter cannot be instantiated with paraless ctor
var someClass = new SomeClass<XmlWriter>();
// causes same compile error for same reason
var someClass = new SomeClass<string>();
Why would you need such constraint? Suppose you want to instantiate the a new variable of type T
. You can only do that when you have this constraint, otherwise, the compiler cannot know beforehand whether the instantiation works. I.e.:
public class SomeClass<T> where T: new()
{
public static T CreateNewT()
{
// you can only write "new T()" when you also have "where T: new()"
return 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