Why isn't a new () general constraint satisfied by a class with optional parameters in the constructor?

The following code cannot be compiled, creating the error "The widget must not be an abstract type with an open constructor without parameters." I would think that the compiler has all the necessary information. This is mistake? Supervision? Or is there some kind of scenario when this is not valid?

public class Factory<T> where T : new()
{
    public T Build()
    {
        return new T();
    }
}

public class Widget
{
    public Widget(string name = "foo")
    {
        Name = name;
    }

    public string Name { get; set; }
}

public class Program
{
    public static void Main()
    {
        var widget = new Widget(); // this is valid
        var factory = new Factory<Widget>(); // compiler error
    }
}
+5
source share
1 answer

Although this should work logically, unfortunately this does not happen. The CLR still sees your constructor as a parameter-based constructor.

, , # , . - . CLR, " " , :

public Widget(([Optional, DefaultParameterValue("foo")] string name) { // ...

CLR - . CLR , . , DefaultParameterValueAttribute, , .


Edit:

:

, # CLR

# , , , . , , "" ( ), . , , - , , API , , . :

public Widget(
          int id = 0, 
          string name = "foo", 
          float width=1.0f, 
          float height=1.0f, 
          float depth=1.0f
       ) { // ... 

, 120 , N! ...

+7

All Articles