locked
Lambda Expression RRS feed

  • Question

  • Can anybody explain this Lambda expression in the following code snippet?
    this.BeginInvoke(new Action(() =>
                    {
                        MessageBox.Show(this, "Test Message", "Test", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }));
    

    Why doesn't call MessageBox.Show directly but use Lambda Expression?
    Friday, December 19, 2014 12:17 AM

Answers

  • Hello,

    BeginInvoke method receive a delegate parameter, it execute the specified delegate asynchronously on the thread that the control's underlying handle was created on.Please check the MSDN document for details:
    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx
    Action is a delegate which receives no parameters and has no returned value:
    http://msdn.microsoft.com/en-us/library/system.action.aspx
    Lambda expression is actually an anonymous function which you can use to create delegates or expression tree types.
    http://msdn.microsoft.com/en-us/library/bb397687.aspx
    http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
    The left side of the operator "=>" stands for the parameters of the delegate, in this case Action delegate doesn't contain a parameter. The right side of the operator "=>" stands for the body of the method.
    This code snippet only asynchrously shows a messagebox actually. For more information of the delegates and anonymous method,please check the MSDN documentation.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Proposed as answer by KareninstructorMVP Sunday, December 21, 2014 7:48 PM
    • Marked as answer by Caillen Monday, December 29, 2014 7:56 AM
    Sunday, December 21, 2014 2:22 PM