As we all know, we cannot write code like this in current version of C#:
public class A {
public static void Method<T> () where T : new(string, string) {
var x = new T("foo", "bar");
}
}
but we may use new()
constrain to enforce that T
has public parameter-less constructor, and then we are able to create new instances of T
using new T()
expression.
There is plenty of answers on SO about various workaround, but non of them explains why language designers not implemented such feature. From amount of questions on SO it looks like it would be useful in read world applications.
Why this feature was not implemented in C#, are there any chances that it will be added in next version of the language?
Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.
According to this feature request link on github, the reason is that the CLR doesn't provide the information that C# needs to implement it.
There is speculation that the CLR may be modified in order for a future C# version (7.0?) to support this feature.
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