i never use new Constraint because the use is not clear to me. here i found one sample but i just do not understand the use. here is the code
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
public class ItemFactory2<T> where T : IComparable, new()
{
}
so anyone please make me understand the use of new Constraint with small & easy sample for real world use. thanks
In addition to Darin’s answer, something like this would fail because
Bardoes not have a parameterless constructorActual error is:
'Bar' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ItemFactory<T>'The following would also fail:
Actual error is:
Cannot create an instance of the variable type 'T' because it does not have the new() constraint