Why isn't the new() generic constraint satisfied by a class with optional parameters in the construc
- by Joshua Flanagan
The following code fails to compile, producing a "Widget must be a non-abstract type with a public parameterless constructor" error. I would think that the compiler has all of the information it needs. Is this a bug? An oversight? Or is there some scenario where this would not be 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
}
}