Event variables and parameters

Topics: C# Language Design
Jul 16, 2014 at 11:31 AM
Edited Feb 11, 2015 at 1:55 PM
Would it be possible for C# to support the assignment of events to variables, e.g.
extern event DownloadStringCompletedEventHandler myVariable = webClient.DownloadStringCompleted;

myVariable += SomeEventHandler;
myVariable -= SomeEventHandler;
I have just used the extern keyword to differentiate between an implemented event and a reference to another event.

One thing which would need to be considered is event references maintaining a reference to the containing object, i.e. the whole time myVariable is alive, webClient must remain alive.

If this assignment to variables was supported, it could also be extended to parameters, e.g.
private static void SubscribeSingle(extern event EventHandler target)
{
    EventHandler handler = null;
    handler = (s, e) =>
    {
        Console.WriteLine("Event raised!");
        target -= handler;
    };
    target += handler;
}
Standard delegates should be assignable to extern events, e.g.
Action myAction = () => { };
extern event Action myActionEvent = myAction;
This is because delegates can have handlers added. On the other hand, the following should be disallowed:
Action myOtherAction = myActionEvent; // NO!
This is because we are not allowed to raise the event from somewhere else.

Like delegates, extern events should also support variance in delegates, i.e.
extern event EventHandler someEvent = new EventHandler(webClient.DownloadStringCompleted);
The logic behind compilation of delegates would need to remember whether the delegate is an extern event or a standard delegate.

My primary reason for considering this is when writing utility methods to adapt from the Event-based asynchronous pattern to the Task-based asynchronous pattern, I got fed up of writing methods which took and addHandler delegate and a removeHandler delegate.

Let me know what everybody thinks, the scope may be too limited but I think it could be nifty and make events that bit easier to work with.