main banner


Methods in .NET - Generic constraints on type parameters (Part 4)

In this article, we will see the details regarding constraints on type parameters at method definition. 

Previously in this article about methods in .NET we covered:

1.- Named and Optional arguments (Part 1)
2.- Parameters with variable number of arguments (Part 2)
3.- Extension methods (Part 3)

Finally on this occasion, we will see the details regarding constraints on type parameters at method definition.

Sometimes we want to have control over generic types received as arguments in a method; by constraining the type, we make sure the argument complies with an interface or has certain attributes or properties important in our business logic.

In our next example we will have three classes/types:

  • Person: with Name property
  • Employee: derives from Person. It adds the Id property
  • Developer: derives from Employee. It also declares the Languages property


Let’s assume that in our business, it is important to validate that all employees from a List have an Id assigned (please notice that in this case for teaching purposes, the Id property is a nullable integer). The method ValidateAllEmployeesHaveAnId uses generics and it basically checks that all the items in the list provided as an argument have an Id assigned. The key for making sure the generic type passed as a list has an Id property is constraining the type, which is achieved by adding the where keyword. In our example we will allow only derived types from Employee: where T : Employee.


With this method definition, handling generic types is accomplished; the following code shows how we can call the method, either by using an Employees list or a Developers list. The resulting output has also been included.



Now, let us try to use a People (Person) list as an argument to the generic type with Employee type constraint method. 


If we compile the code, we get an error: the Person type cannot be used as a generic type for the method. 


The benefit for adding constraints to the method is that we are guaranteeing, through the compiler, that the type passed is supported by our method. More information on how to use the constraints on type parameters can be found in Constraints on Type Parameters (C# Programming Guide).

Osvaldo G.

Calling Osvaldo “el Doc” is no coincidence, he is part of the Inflection Point’s gurus and has been working in the company for 9 years; his degree in Computer Engineering, the numerous certifications and more than 15 years of experience in Microsoft technologies, have made of him a mentor for many and also an avid writer for Inflection Point’s blog with tips and facts that have saved more than one coder in their quest for better coding. He comes from San Nicolás de los Garza, Nuevo Leon and is a Tigres (local soccer team) fan.