Type Parameter Constraint is a class

I noticed that other developers used this technique, but it always confused me. I decided to research this morning and stumbled upon MSDN (from http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.100).aspx ):

public class GenericList<T> where T : Employee
{
...
}

Why do we want to use this method instead of replacing all instances of T with Employee in the class? For me, it seems like a win for maintainability. I can understand by restricting the interface as a means of including classes from different inheritance hierarchies, but inheritance already solves the problem above in a more obvious way, doesn't it?

Can this be considered a mistake, or would it be a mistake to “fix” such a code?

+3
source share
4 answers

-, Employee.

public class EvilEmployee : Employee {
    public Int32 Evilness { get; set; }
}

...

GenericList<EvilEmployee> list = GetEvilEmployees();
var mostEvilEmployee = list.OrderByDescending(e => e.Evilness).First();

, , T = EvilEmployee EvilEmployee Evilness. Employee, ( OfType).

+7

T Employee ?

:

class Manager : Employee { ... }

var board = new GenericList<Manager> ();

, "GenericList" "EmployeeList"

,

.

, ?

, . board.Add(lowlyProgrammer); , .

+5

If the expression is added specifically. Think about a situation where there are classes originating from the Employee class; if you do not define a generic class, you need to define a class for each derived class.

For example, if EmployeeX inherits Employee, and you want to define a List only by accepting instances of EmployeeX using the general approach, you do not need to define a new class.

0
source

Generics allow you to be typical without the need for a cast.

if you have

  public class Manager : Employee
  {
     public double CalculateManagerBonus();
  }

You can do

   GenericList<Manager> managers = ....

   managers[0].CalculateManagerBonus();

if you have

   GenericList<Employee> managers = ....

   // this is a compiler error
   managers[0].CalculateManagerBonus();

  // this is neccessary if there where no generics.
  ((Manager)managers[0]).CalculateManagerBonus();
0
source

All Articles