Reputation: 46108
I've been having a looksie at the .NET CLI spec, and although it mentions you can have a default constructor constraint on a generic type paramter, it doesn't specify anything you can then do with such a generic type to actually create it. What's the official 'spec' way of actually creating an instance of a generic type with a constructor constraint?
Upvotes: 1
Views: 254
Reputation: 700362
It's not a default constructor constraint, it's a parameterless constructor constraint. The class has to have a parameterless constructor, regardless if that constructor is the implicitly created default constructor or an explicitly declared parameterless constructor.
Both of these classes fulfill the constraint:
public class A {
}
public class B {
public B() { }
}
But not this one, as there is no implicitly created constructor if you have any explicitly declared constructors:
public class C {
public C(int id) { }
}
As it's a parameterless constructor, there is only one way to use it:
T item = new T();
It's odd if there is no mention of that in the spec, but it's at least clearly described in MS's C# reference: new Constraint. A spec is however not meant to be read ion the same way as documentation, so it might be hard to find exactly where it's mentioned, and it might only be mentioned once.
Upvotes: 0
Reputation: 1062875
Simply:
public static void CreateThings<T>() where T : new() {
T t = new T();
// now either return t or do other things with it, particularly
// when combined with interface constraints
}
To quote the spec sections from ECMA 334 v4
The type of an object-creation-expression shall be a class-type, a value-type, or a type-parameter having the constructor-constraint or the value type constraint (§25.7).
...
Otherwise, if T is a type-parameter:
- If A is present, a compile-time error occurs.
- Otherwise, if T has the constructor-constraint or the value type constraint, the result of the objectcreation- expression is a value of type T.
- Otherwise, the object-creation-expression is invalid, and a compile-time error occurs.
Upvotes: 1
Reputation: 81660
You can use the constructor in the generic type:
return new T();
Upvotes: 0