In C#, there are two terms defined regarding delegates; Covariance and Contravariance. These two concepts exapand the set of methods that you can assign to a delegate. They still maintain type-safeness. I’d better clarify it using an example. Suppose that you have these classes:
public class P1
{
…
}
public class C1 : P1
{
…
}
public class P2
{
…
}
public class C2 : P2
{
…
}
And you have a delegate defined this way:
public delegate P1 myDelegate(C2 c2);
If you intend to use this delegate, you will have to assign a method with a same signature. For example:
public P1 myMethod(C2 c2)
{
…
}
But not only can you use any method with a return type of P1, but any child class of P1 (in this case C1) in the chain of hierarchy. This is called Covariance.
On the other hand, you can use any method with a paramater of type C2 or any super type of C2 (in this case P2). This is called Contravariance.
No comments:
Post a Comment