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.
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) { .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With