Difference between Covariance and Contravariance delegates in .NET

When you assign a method to a delegate, the method signature does not have to match the delegate exactly. This is called covariance and contravariance.

Covariance

Covariance makes it possible that a method has a return type that is more derived than that defined in the delegate.

public delegate TextWriter CovarianceDel();
public StreamWriter MethodStream() { return null; }
public StringWriter MethodString() { return null; }
CovarianceDel del;
del = MethodStream;
del = MethodString;

Because both StreamWriter and StringWriter inherit from TextWriter, you can use the CovarianceDel with both methods. However, the other way round is not possible.

Contravariance

Contravariance permits a method that has parameter types that are less derived than those in the delegate type.

void DoSomething(TextWriter tw) { }
public delegate void ContravarianceDel(StreamWriter tw);
ContravarianceDel del = DoSomething;

The method DoSomething takes TextWriter as its parameter. Since, StreamWriter is derived from TextWriter, we can also pass the object of StreamWriter to the method DoSomething through this delegate instead of TextWriter.

More Info:- http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s