Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event and delegate contravariance in .NET 4.0 and C# 4.0

While investigating this question I got curious about how the new covariance/contravariance features in C# 4.0 will affect it.

In Beta 1, C# seems to disagree with the CLR. Back in C# 3.0, if you had:

public event EventHandler<ClickEventArgs> Click; 

... and then elsewhere you had:

button.Click += new EventHandler<EventArgs>(button_Click); 

... the compiler would barf because they're incompatible delegate types. But in C# 4.0, it compiles fine, because in CLR 4.0 the type parameter is now marked as in, so it is contravariant, and so the compiler assumes the multicast delegate += will work.

Here's my test:

public class ClickEventArgs : EventArgs { }  public class Button {     public event EventHandler<ClickEventArgs> Click;      public void MouseDown()     {         Click(this, new ClickEventArgs());     } }  class Program {         static void Main(string[] args)     {         Button button = new Button();          button.Click += new EventHandler<ClickEventArgs>(button_Click);         button.Click += new EventHandler<EventArgs>(button_Click);          button.MouseDown();     }      static void button_Click(object s, EventArgs e)     {         Console.WriteLine("Button was clicked");     } } 

But although it compiles, it doesn't work at runtime (ArgumentException: Delegates must be of the same type).

It's okay if you only add either one of the two delegate types. But the combination of two different types in a multicast causes the exception when the second one is added.

I guess this is a bug in the CLR in beta 1 (the compiler's behaviour looks hopefully right).

Update for Release Candidate:

The above code no longer compiles. It must be that the contravariance of TEventArgs in the EventHandler<TEventArgs> delegate type has been rolled back, so now that delegate has the same definition as in .NET 3.5.

That is, the beta I looked at must have had:

public delegate void EventHandler<in TEventArgs>(object sender, TEventArgs e); 

Now it's back to:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e); 

But the Action<T> delegate parameter T is still contravariant:

public delegate void Action<in T>(T obj); 

The same goes for Func<T>'s T being covariant.

This compromise makes a lot of sense, as long as we assume that the primary use of multicast delegates is in the context of events. I've personally found that I never use multicast delegates except as events.

So I guess C# coding standards can now adopt a new rule: don't form multicast delegates from multiple delegate types related through covariance/contravariance. And if you don't know what that means, just avoid using Action for events to be on the safe side.

Of course, that conclusion has implications for the original question that this one grew from...

like image 424
Daniel Earwicker Avatar asked Jul 13 '09 16:07

Daniel Earwicker


People also ask

Which delegates support covariance and contravariance in C#?

NET Framework 4 and later versions, C# supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters. For more information, see Variance in Generic Interfaces (C#) and Variance in Delegates (C#).

What is the relationship between events and delegates in C#?

Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.

What is delegate in C#?

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

What is covariance and contravariance in generics?

Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.


1 Answers

Very interesting. You don't need to use events to see this happening, and indeed I find it simpler to use simple delegates.

Consider Func<string> and Func<object>. In C# 4.0 you can implicitly convert a Func<string> to Func<object> because you can always use a string reference as an object reference. However, things go wrong when you try to combine them. Here's a short but complete program demonstrating the problem in two different ways:

using System;  class Program {         static void Main(string[] args)     {         Func<string> stringFactory = () => "hello";         Func<object> objectFactory = () => new object();          Func<object> multi1 = stringFactory;         multi1 += objectFactory;          Func<object> multi2 = objectFactory;         multi2 += stringFactory;     }     } 

This compiles fine, but both of the Combine calls (hidden by the += syntactic sugar) throw exceptions. (Comment out the first one to see the second one.)

This is definitely a problem, although I'm not exactly sure what the solution should be. It's possible that at execution time the delegate code will need to work out the most appropriate type to use based on the delegate types involved. That's a bit nasty. It would be quite nice to have a generic Delegate.Combine call, but you couldn't really express the relevant types in a meaningful way.

One thing that's worth noting is that the covariant conversion is a reference conversion - in the above, multi1 and stringFactory refer to the same object: it's not the same as writing

Func<object> multi1 = new Func<object>(stringFactory); 

(At that point, the following line will execute with no exception.) At execution time, the BCL really does have to deal with a Func<string> and a Func<object> being combined; it has no other information to go on.

It's nasty, and I seriously hope it gets fixed in some way. I'll alert Mads and Eric to this question so we can get some more informed commentary.

like image 62
Jon Skeet Avatar answered Oct 03 '22 00:10

Jon Skeet