Relation between generic type parameter and generic type definition is known as variance.
Covariance and contravariance are extensions for generic type parameters for arrays, delegates and interfaces.
1.COVARIANCE- In Covariance 'out' keyword is used to declare input parameter. It keeps the work compatible. In covariance, where IEnumerable<object> is expected we can use IEnumerable<string> in place of that.
e.g of covariance:-
public interface IEnumerable<out T>
{
IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<out T>
{
T Current { get; }
bool MoveNext();
}
2.CONTRAVARIANCE:- The functions of contravariance are just different from covariance. Input parameters are passed by using 'In' keyword.
e.g of contravariance:-
void DoSomethingToAFrog(Action<Frog> action, Frog frog)
{
action(frog); }
... Action<Animal> feed = animal=>{animal.Feed();}
DoSomethingToAFrog(feed, new Frog());
0 Comment(s)