You say that you're reading about
Action
delegates and then ask whether we need delegates any more. You seem to have answered your own question.
It helps to understand what a delegate is and what an event is, so you understand how the inner working relate to what we see on the outside. The term "delegate" is used to refer to types and objects. Delegate types are special classes that can refer to methods with particular signatures. A delegate object is an instance of one of those types. For instance, the
Action
delegate can refer to methods with no parameters and that do not return anything. The
Comparison<T>
delegate can refer to methods that have two parameters of type
T
, i.e. any type but both the same, and that return an
int
. The
EventHandler
delegate can refer to methods that have two parameters of type
object
and
EventArgs
and that do not return anything. Etc.
An event is basically a special property that refers to a collection of delegates. The act of raising an event actual involves looping through the delegates in that collection and invoking each one. Invoking a delegate means executing the method it refers to.
What you have been reading about is almost certainly just the use of a Lambda expression as the method referred to by an event delegate instead of a named method. The actual event mechanism doesn't change in any way. In both cases, you create an appropriate delegate and that gets added to the collection of delegates stored in the event. Look at this code:
private void Form1_Load(object sender, EventArgs e)
{
var btn1 = new Button {Text = "Button1"};
btn1.SetBounds(10, 10, 100, 25);
btn1.Click += Button_Click;
var btn2 = new Button {Text = "Button2"};
btn2.SetBounds(10, 50, 100, 25);
btn2.Click += (s, ea) => Console.WriteLine("Click via Lambda expression");
Controls.AddRange(new[] {btn1, btn2});
}
private void Button_Click(object sender, EventArgs e)
{
Console.WriteLine("Click via named method");
}
One event handler is created from a named method and the other is created from a Lambda expression but the events don't care. In both cases, they simply add a delegate to their collection and then invoke it when the event is raised.