So I was looking at the MSDN example here: Constraints on Type Parameters (C# Programming Guide) and the 1st example shows the following generic class defining a where constraint with a single concrete type: Employee
public class GenericList<T> where T : Employee
Now when using a where constraint I totally understand the use when defining > 1 type, or most certainly when using an Interface. However (and I know it was only an example), why would I ever want to just use a where constraint to restrict to a single concrete type? Couldn’t I just replace the code below:
public T FindFirstOccurrence(string s)
with the following since there is only a single constraint anyway?
public Employee FindFirstOccurrence(string s)
The only reason I could see deploying code with a single where constriant is for flexibility in the future to add additional constraints for if Employee became IEmployee and I was set up a bit easier for the changes.
Can someone explain what purpose using a where constraint for a single type provides?
Thanks!
Not quite right there – the constraint is on the
Employeetype and any type that inherits from it, so it can apply toManagerandCEOclasses as well.Defining the constraint means you can use any accessible methods on the
Employeetype inside your code, whether the passes in type is anEmployeeor an inheriting type.