Example 1 (does not compile):
void Main()
{
var c = new C<D>();
c.M.F();
}
class C<T>
{
T _m = null;
public T M { get {
if(_m == null) _m = new T();
return _m;
} }
}
class D
{
public void F() { Console.WriteLine ("i was created"); }
}
Result:
Cannot create an instance of the variable type ‘T’ because it does not have the new() constraint
Example 2 (works):
void Main()
{
var c = new C<D>();
c.M.F();
}
class C<T>
{
Lazy<T> _m = new Lazy<T>();
public T M { get { return _m.Value; } }
}
class D
{
public void F() { Console.WriteLine ("i was created"); }
}
Result:
i was created
If you delve into the source code, you’ll see that
Lazy<T>ultimately usesActivator:This is just a shortcut for using reflection. Since it’s not instantiating the type via the actual generic type argument (
new T()) but rather invoking the constructor through reflection, nowhere T : new()constraint is needed.