Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no constructor-with-parameters constrain on generic parameters in C#?

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?

like image 484
csharpfolk Avatar asked Jan 17 '16 13:01

csharpfolk


People also ask

What is the purpose of the class constraints on a type parameter?

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.

What constrains can be applied to generics C#?

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.

Which of the following generic constraints restricts the generic type parameter to an object of the class?

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.


1 Answers

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.

like image 111
Frank Bryce Avatar answered Sep 28 '22 16:09

Frank Bryce