Open Source Your Knowledge, Become a Contributor

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.

The below code shows you can create your own generic class, run it to see test results

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

·namespaceGenericsLesson

{

classLesson<T>

{

privateTt;

publicvoidSet(Tt){

this.t=t;

}

publicTGet()

{

returnt;

}

}

}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

1

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.