Back
Close

Demystifying C# Generics

AramT
27.7K views

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
·namespace GenericsLesson
{
class Lesson<T>
{
private T t;
public void Set(T t){
this.t = t;
}
public T Get()
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.

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.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants