-4

How does addition assignment operator behaves here -

btn.Click += delegate(object sender, EventArgs e)
nicholas
  • 125
  • 8
  • i understand that x+= y means x = x + y, but what with the events – nicholas Sep 30 '15 at 06:55
  • this is how you assign an event handler to btn.click event in c# – Kayani Sep 30 '15 at 06:59
  • refer to: https://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx for more details – Kayani Sep 30 '15 at 07:00
  • 1
    This is what I typed in Google "c sharp += delegate" and what I have got under the second link [C# - Delegates](http://www.tutorialspoint.com/csharp/csharp_delegates.htm) in section: "Multicasting of a Delegate" - _Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate._ Honestly, it's pure laziness. – Celdor Sep 30 '15 at 07:01
  • is it what is called anonymous method? – nicholas Sep 30 '15 at 07:04
  • delegates are objects with name which must be instantiated. Their purpose is to define a sort of placeholder if you want to pass and then invoke a function e.g. inside an another method / function. A _Anonymous function_ on the other hand is a function without name, defined and instantiated inline. E.g., `TypeOutput = delegate(TypeINput variable) { // body of a function };`. The latter is superseded by Lambda Expressions from c# 3.0 onward. I cannot fully explain this in this comment, I am afraid. – Celdor Sep 30 '15 at 07:34

1 Answers1

2

It adds an event handler to the event Click. When Click event is raised all the handlers method added to it are called.

For example:

void BtnClickHandler1(object sender, EventArgs e)
{
    MessageBox.Show("BtnClickHandler1");
}

void BtnClickHandler2(object sender, EventArgs e)
{
    MessageBox.Show("BtnClickHandler2");
}

And you add these methods to Click event like this:

btn.Click += BtnClickHandler1
btn.Click += BtnClickHandler2

When button is clicked the methods will be called in the order you added them, so the message box will be:

BtnClickHandler1
BtnClickHandler2

If you want specific info about += operator, MSDN says:

The += operator is also used to specify a method that will be called in response to an event; such methods are called event handlers. The use of the += operator in this context is referred to as subscribing to an event.

For more info look at:

https://msdn.microsoft.com/en-us/library/edzehd2t%28v=vs.110%29.aspx

http://www.dotnetperls.com/event

Matteo Umili
  • 3,412
  • 1
  • 19
  • 31