Covariance and Contravariance for Delegates

6/6/2004 12:36:06 AM

Covariance and Contravariance for Delegates

According to the Whidbey help, contravariance of delegate parameters and covariance of return types may be supported for delegates in the Whidbey release. Variance was mentioned in a prior Don Box post. In .NET 1.1, delegates could only be created with methods whose arguments strictly matched the signature of that delegate. Now, it appears the requirements may been relaxed to allow methods with compatible signatures (though I haven't actually noticed any changes to the C# spec to reflect this).

Note the help documentation is still incomplete and the feature and its availability is subject to change. I have yet to test this out on the May CTP as I have had repeated installation failures, but I have been wishing for this feature.

Suppose we have three classes.

public class MyBase
{
}

public class MyClass : MyBase { }
public class MyDerived : MyClass { }

and a delegate defined as follows:

public delegate MyClass MyDelegate(MyClass arg);

Covariance
Covariance of return values allows a delegate of type, say D, to wrap a method whose return value is of a type, which derives from or equals the return value type of D.

For example, MyDelegate may match the following as a result of covariance:

MyDerived Foo(MyClass arg);

Note that the MyDelegate will not match Foo if the return type was that of a base class, because that would not be compatible with the original signature of the delegate.

Contravariance
Contravariance of methods parameters allows a delegate of type D to wrap a method whose parameters have a type, which is either a base class of or the same class of the type of the corresponding parameter in the signature of D.

For example, MyDelegate may match the following as a result of contravariance:

MyClass Foo(MyBase arg);

Note that the MyDelegate will not match Foo if the parameters are of derived types instead of base types, for compatibility reasons as well.

Comments

 

Navigation

Categories

About

Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media