C# Generic — 01

Rasika Gayan Gunarathna
4 min readJul 16, 2022

--

First, check how to define a generic class.

We defined the generic class as above. We can call it Repository[Class name] of T.

So we can define some classes in a school management system.

So now we have two Entity classes.

Let’s create a generic repository class.

After creating instances.

Generic class inheritance

If we inherited a generic class to a non-genric class, we need to define the type in there. (change the superclass _dataset access modifier to protected )

But also we can create a generic sub-class.

Constraints on generic type parameters

If we add the below method to the repository class, it will give an error

Because type T doesn’t know whether the concrete type will have an Id property or not, so we need to add a constraint that all the types that pass to this will have Id prop.

So we can encapsulate the Id and use it as a superclass

Change the Repository class

We only define IEntity type in type constraint. So that means T can be value type or reference type.

But if we added EntityBase , that means we need to be T as EntityBase type. That means T must be reference type.

If we only add IEntity , we can’t return null from a below method.

Because T can be null-nullable value type.

So we can update as below.

As a important point if we want to return null as explicitly we need to define that T is a reference type. So we add that T is a reference type add class keyword.

We can add ? mark as this can be nullble reference type.

If we want to return a instance of type T we need to add new() to the end.

Impotant thing is we need to make sure passing type need to have default constructor.

--

--

Rasika Gayan Gunarathna

Full Stack Developer | AWS Associate Solution Architect | Skater