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.
-
Archives
- February 2009 (1)
- November 2008 (6)
- October 2008 (4)
- September 2008 (13)
- August 2008 (11)
- July 2008 (29)
- June 2008 (19)
- May 2008 (8)
-
Categories
-
RSS
Entries RSS
Comments RSS

