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?
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.
Generic classes and methods
Generics introduces the concept of type parameters to .NET, which make it possible to design classes and methods that…