Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Delegates : Contravariance and Covariance

When are delegates compatible or similar? The parameters of the function pointer can be derivations of the parameters indicated in the delegate signature—this is called contravariance. Because the delegate parameters refine that of the function pointer, any input from the target method is acceptable to the delegate. Conversely, the return type of the delegate must be a derivation of the return type of the function pointer. The return of the function pointer can refine the return of the delegate. Therefore, any return from the delegate is compatible with that of the function pointer—this is called covariance. Contravariance and covariance expand the set of methods assignable to a delegate while maintaining type-safeness. Here is an example of both contravariance and covariance:

using System;

 

namespace Examples.Delegates

{

    delegate ZClass DelegateClass(BClass obj);

    public class Program

    {

        public static void Main()

        {

            DelegateClass del = MethodA;

        }

 

        public static YClass MethodA(AClass obj)

        {

            return null;

        }

    }

 

    public class ZClass

    {

    }

 

    public class YClass : ZClass

    {

    }

 

    public class AClass

    {

    }

 

    public class BClass : AClass

    {

    }

}

In the preceding code, this is the signature of the delegate:

delegate ZClass DelegateClass(BClass obj);

This is the signature of the function pointer:

public static YClass MethodA(AClass obj)

The signature of the delegate and function pointer are not exactly the same. This is okay because the parameter of the delegate (BClass) refines the parameter of the function (AClass), which is contravariance. In addition, the return type of the function (YClass) refines the return type of the delegate (ZClass). This is covariance.

August 14, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet