Home > Article > Backend Development > Covariance and contravariance in C#
To deal with classes efficiently, use the concepts of covariance and inverse variance.
Let's consider the following as our course. One is the base class for class two, and two is the base class for class three.
class One { } class Two: One { } class Three : Two { }
Base classes can contain derived classes, but the reverse is not possible. Covariance allows you to pass a derived type where a base type is expected. Covariance can be used with arrays, interfaces, delegates, etc. in C#.
The contrast variance is for parameters. Allows methods with base class parameters to be assigned to delegates that require derived class parameters with contravariance.
The above is the detailed content of Covariance and contravariance in C#. For more information, please follow other related articles on the PHP Chinese website!