When you define an Event Handler using Lambda notation, the resulting method is "anonymous" in the sense it's not available to be manipulated by the programmer once it has been created
unless you keep a reference to it. That's really the same "visibility" logic that applies to anything you create within the
scope of a some method, class, etc.
And, of course, you
can maintain a reference to an Event Handler created "inline;" a reference you can, at any time, remove in the standard way you remove an Event Handler from a Multicast Delegate.
Assume you have two Button Controls on a WinForm, button1, button2: consider the following code:
EventHandler Button1Click;
MouseEventHandler Button2MouseDown;
private bool AreEventsWired = false;
private void button1_Click(object sender, EventArgs e)
{
AreEventsWired = ! AreEventsWired ;
if (AreEventsWired )
{
Button1Click = (object obj, ea) => { MessageBox.Show("Button1 Click"); };
button1.Click += Button1Click;
Button2MouseDown = (object obj, MouseEventArgs ea) => { MessageBox.Show("Button2 MouseDown"); };
button2.MouseDown += Button2MouseDown;
}
else
{
button1.Click -= Button1Click;
button2.MouseDown -= Button2MouseDown;
}
}
Can you predict what will happen, or not happen, the first and second time, you click on button1 at run-time ?
[1] note that here we do not specify the parameter Types in our Lambda form EventHandler declaration: the compiler assumes that we are using the default Types, Object, and EventArgs.
[2] note that here the compiler
requires we specify
both Types, Object, and MouseEventArgs because MouseEventArgs is not the
default EventHandler event-argument Type.
Discussion: if you really think about it you'll see that all we have really done in the above example is just use a fancy way to create a defined EventHandler. Its usage will be exactly the same as if you had created a named EventHandler in a separate method.
So, when your code does require you keep a reference to an EventHandler, unless you are really thrilled by the act of writing Lambda notation: you might well ask yourself if there's any advantage to writing code this way.
Further Out: if C# gave us direct access programmatically to the "guts" of MultiCast Delegates, so we could dynamically inspect which EventHandlers were wired-up, and mess around with them: well, that would be another language ?