Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constraints on type parameters – new()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading