Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this line of C# code actually do?

I'm trying to understand what a block of code in an application does but I've come across a bit of C# I just don't understand.

In the code below, what does the code after the "controller.Progress +=" line do?

I've not seen this syntax before and as I don't know what the constructs are called, I can't google anything to find out what this syntax means or does. What for instance, are the values s and p? Are they placeholders?

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    using (var controller = new ApplicationDeviceController(e.Argument as SimpleDeviceModel))
    {
        controller.Progress += 
           (s, p) => { (sender as BackgroundWorker).ReportProgress(p.Percent); };
        string html = controller.GetAndConvertLog();
        e.Result = html;
    }
}

It looks like it's attaching a function to an event, but I just don't understand the syntax (or what s and p are) and there's no useful intellsense on that code.

like image 399
NickG Avatar asked Dec 06 '22 07:12

NickG


1 Answers

It's a lambda expression being assigned to an event handler.

S and P are variables that are passed into the function. You're basically defining a nameless function, that receives two parameters. Because C# knows that the controller.Progress event expects a method handler with two parameters of types int and object, it automatically assumes that the two variables are of those types.

You could also have defined this as

controller.Progress += (int s, object p)=> { ... }

It's the same as if you had a method definition instead:

controller.Progress += DoReportProgress;
....
public void DoReportProgress(int percentage, object obj) { .... }
like image 156
Eduardo Scoz Avatar answered Jan 04 '23 03:01

Eduardo Scoz