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

C# Generic with class constraint

I am studying C# and generics with class constraint like

public class GenericList<T> where T : Employee

I am puzzled because I see nothing generic here. The GenericList list is bound to the Employee’s class. It would be same as if we inject Employee from the GenericList’s constructor.

Or I am missing something?

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 :

I see nothing generic here

That’s what the <T> is after the name of the type (GenericList). T is the name of the generic parameter.

The GenericList list is bound to the Employee’s class.

T can be an Employee, or it can be any type that inherits Employee, either directly or through another type.

It would be same as if we inject Employee from the GenericList’s constructor.

Not really. What you do in the constructor really has nothing to do with the generic parameter. Generics allow you to modify the type. For example, you can have these different variables.

GenericList<Employee> a;
GenericList<FullTimeEmployee> b;
GenericList<PartTimeEmployee> c;

These are all different types.

Dependency injection just works with parameters in the type’s constructor. Yes, those parameter can include types that have generic arguments (for example, you can ask for an ILogger<MyService>), but they T type you specify doesn’t really have a parallel otherwise.

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