Why isn't the new() generic constraint satisfied by a class with optional parameters in the construc
Posted
by Joshua Flanagan
on Stack Overflow
See other posts from Stack Overflow
or by Joshua Flanagan
Published on 2010-04-30T17:25:01Z
Indexed on
2010/04/30
17:37 UTC
Read the original article
Hit count: 153
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
}
}
© Stack Overflow or respective owner