As per MSDN, the new() constraint is used to ensure that the type argument must have a public parameterless constructor. However, consider the example given below (taken from the same page).
public class Employee
{
public Employee(string name, int id)
{
Name = name;
ID = id;
}
public string Name { get; set; }
public int ID { get; set; }
}
class EmployeeList<T> where T : Employee, new()
{
}
Here, the Employee type does not have a parameterless/default constructor, yet this code compiles successfully. Can someone please elaborate on the usage of this constraint and why this works?
>Solution :
The code compiles because it’s entirely possible to have a type derived from Employee with a parameterless constructor – and that’s what the constraint says. The constraint is not trying to say that Employee itself has a parameterless constructor, and indeed an attempt to use EmployeeList<Employee> would fail as the constraint isn’t satisfied.
As example of what would be valid:
public class GeneratedEmployee : Employee
{
public GeneratedEmployee() : base(GenerateName(), GenerateId())
{
}
private static string GenerateName()
{
// Implementation here
}
private static int GenerateId()
{
// Implementation here
}
}
At that point, it’s fine to create an EmployeeList<GeneratedEmployee>, and assuming the EmployeeList<> class uses new() somewhere in the implementation, it would call the parameterless constructor of GeneratedEmployee.
That said, it’s a pretty odd constraint, as I wouldn’t expect you to really want to create an employee without specifying the name and ID.