Covariance and Contravariance in C#

CsharpProgrammingServer Side Programming

To deal with classes effectively, use the concept of covariance and contra variance.

Let us consider the following as our class. One is a base class for class Two, whereas Two is a base class for Three.

class One { 
}
class Two: One {
}
class Three : Two { 
}

A base class can hold a derived class, but the opposite is not possible. With Covariance, you can pass a derived type where a base type is expected. Co-variance can be used on array, interface, delegates, etc in C#.

Contra variance is for parameters. A method with the parameter of a base class is allowed to be assigned to a delegate that expects the parameter of a derived class with Contravariance.

raja
Published on 17-Sep-2018 12:07:33
Advertisements