Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Parameter Constraint is a Class

I've noticed other developers using this technique, but it always confused me. I decided to investigate this morning and came across the following on MSDN (from http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.100).aspx):

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

Why would we want to use this method instead of replacing all instances of T with Employee in the class? To me, this seems like a win on maintainability. I can understand restricting to an 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?

Could this be considered a mistake, or would it be a mistake to 'fix' code like this?

like image 244
Sprague Avatar asked Oct 21 '25 04:10

Sprague


2 Answers

Because it could be something derived from Employee.

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

It's now possible to do...

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

It's possible since we know, at compile time, that T = EvilEmployee and that EvilEmployee has an Evilness property. If we were to force the list into a list of Employee that wouldn't be possible (without using OfType).

like image 93
sisve Avatar answered Oct 23 '25 19:10

sisve


Why would we want to use this method instead of replacing all instances of T with Employee in the class?

To enable:

class Manager : Employee { ... }

var board = new GenericList<Manager> ();

Note that your name 'GenericList' would in this scenario be more like 'EmployeeList'

I can understand restricting to an interface as a means of including classes from different inheritance hierarchies

Class inheritance and interfaces have much in common.

but inheritance already solves the problem above in a more obvious way, doesn't it?

Yes, but it's not the same. board.Add(lowlyProgrammer); will fail here while inheritance would allow it.

like image 26
Henk Holterman Avatar answered Oct 23 '25 18:10

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!