Loading [Contrib]/a11y/accessibility-menu.js

Demystifying C# Generics

AramT
48.5K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Now we will be creating a generic class. You create it the same way you create a normal class, but you just add the parameter T at the end of the class name. You can define the parameter T everywhere inside the class, with members, properties, methods.

To call the Lesson class with the concrete type, you will need to initialize the object with the tags < > , and inside it you should specify the concrete type you want to create your Lesson class with.

Can we have a generic constructor? No, generic constructors are not allowed. Which means that you cannot define the parameter T on the constructor itself.

Read Jon Skeet's answer on stackoverflow regarding generic constructors.

You can still use a factory creator static method and define to it the parameter T, but still I don't think you really need that in most of the cases.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content