Search code examples
c#asp.netcsharpcodeprovider

How does addition assignment operator behave


How does addition assignment operator behaves here -

btn.Click += delegate(object sender, EventArgs e)

Solution

  • 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