Covariance and Contra-variance C# Help

The method that is invoked by the delegate does not need the exact same types as defined by the delegate declaration. Covariance and contra-variance are possible.

Return Type Covariance

The return type of a method can derive from the type defined by the delegate, In the example the delegate MyDelegatel is defined to return the type DelegateReturn. The method that is assigned to the delegate instance did returns the type “”gateReturn2 that derives from the base class DelegateReturn and thus fulfills the re if ints of the delegate. This behavior is known by the name return type covariance.

public class DelegateReturn
{
}
public class DelegateReturn2 DelegateReturn
{
} ‘I
public delegate DelegateReturn MyDelegate1();
class Program

                  static void Main{)
MyDelegatel dl Methodl;
dl ();
s                          tatic DelegateRet~rn2 Methodl()
DelegateReturn2 d2 = new DelegateReturn2();
return d2

Parameter Type Contra-variance

The term parameter type contra-variance means that the parameters defined by the delegate might differ in the method that is called by the delegate. Here it’s different from the return type because the method might use a parameter type that derives from the type defined by the delegate. In the code sample the delegate uses the parameter type DelegateParam2, and the method that is assigned to the delegate instance 02 uses the parameter type DelegateParam that is the base type of DelegateParam2.

Posted on October 28, 2015 in Delegates and Events

Share the Story

Back to Top