I would pass a control of my form to another class where I will be creating events for the control, its parent control etc. I also need to detach those events at some point. But I need to ensure I wont be duplicating the events, if the event is already attached.
So I always attach events like this, for eg:
internal static void X(Control c, MouseEventHandler mouseDownEvent)
{
c.TopLevelControl.MouseDown -= mouseDownEvent;
c.TopLevelControl.MouseDown += mouseDownEvent;
}
Now I would need similar event attaching for other handlers too. For eg,
internal static void X(Control c, EventHandler event)
{
c.Enter -= event;
c.Enter += event;
}
Now I dont want to spray around this -= and += all around, instead would like to have one simple utility function so that I can call it everywhere.
Something like:
internal static void AttachEvent(this Control c,
Func<Control, MouseEventHandler> e,
MouseEventHandler m)
{
e(c) -= m;
e(c) += m;
}
So that I can call:
AttachEvent(c, control => control.MouseDown, mouseDownEvent);
But this wouldn’t compile, I get two errors:
The event 'System.Windows.Forms.Control.MouseDown' can only appear on the left hand side of += or -=
and
The left-hand side of an assignment must be a variable, property or indexer
I would like to have the AttachEvent take any event as input argument, but if that’s too complicated, I can live with the MouseEvents alone.
I think this is not possible. Event in C# – like a property – consists of two methods: add and remove. So if you expand event in two methods in your mind
you will see it is not possible to pass reference to event and do something with it in other method.
Also += is part of C# syntax and only works with referencing event at left side of expression.