Reza Najafi Reza Najafi - 24 days ago 23
C# Question

What is += operator doing in the provided C# code?

What does this

+=
operator means in this code, is it a lambda?
I read the MSDN document for the lambda but didn't find any thing about this
+=
operator, I will be thankful if someone explain it to me

translateButton.Click += (object sender, EventArgs e) =>
{
translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (String.IsNullOrWhiteSpace(translatedNumber))
{
callButton.Text = "Call";
callButton.Enabled = false;
}
else
{
callButton.Text = "Call " + translatedNumber;
callButton.Enabled = true;
}
};

Answer

As an arithmetic operation +=/-= mean

add/subtract the right side to/from the left side and assign the result to the left side.

So writing a += 5 is the same as writing a = a + 5.

This code, however, is about events and event handlers. In the context of event handlers, +=/-= mean

add/remove the following delegate to/from the list of event handlers for this event.

So your sample code adds a new event handler to the button's Click event. The way it is written is called inline implementation.

Please note that in the context of event handlers, you can usually not replace

Event += Handler;

by

Event = Event + Handler;

as there is no way to "read" the Event "property" outside the implementing class.

Comments