C# Generic — 02

If the interface has generic constraints, its implemented class need to define these constraints too. See the below image.

Invariant, Covariant and Contravarince

What is Invariant?

In an interface, generic type parameters are invariant because Interface and class implementation have the same generic parameter type.

(See the same type parameter as Teacher type)

We can define covariant by using the “out” keyword because we can have a less specific type in methods.

But other methods need to have contravariantly valid.

So we can divide it into 2 interfaces for this solution.

After fixing all solutions would be like below.

The main point is that we have a PrintAll method that uses for all.

What is the importance of Generic Interfaces?

Contravariance

We can avoid the above by doing as following .

But now we get a new error that we can’t pass IRepositoryType<Teacher> to the above method. Because it is default invariant.

To resolve that we can change the interfaces as below.

And change the method parameter to as below.

Proof of D in SOLID: Component only deepened on abstraction, not in the implementation.

Reference:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rasika Gayan Gunarathna

Rasika Gayan Gunarathna

Full Stack Developer | AWS Associate Solution Architect | Skater