-3

I am new to programming in C#, and I know that videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage); will run the Console.WriteLine whenever the videoDownloader.DownloadProgressChanged is called. But I don't know how to have more than one line in that function.

I want to be able to have something like:

videoDownloader.DownloadProgressChanged += (sender, args)
{
    if ((args.ProgressPercentage % 1) == 0)
    {
        Console.WriteLine(args.ProgressPercentage);
    }
}

Also, can someone explain to me what this is (and what it is called) and how/when this kind of thing is used?

Muhammad Khan
  • 991
  • 1
  • 12
  • 26
  • 1
    if you are a beginner then you would definitely want to define a real function instead of using an anonyms one – Steve Nov 30 '17 at 21:12
  • 1
    Just put a `=>` after the parens with the arguments, just like in the one-line version you had: `(sender, args) => { ...`. Somebody's going to get 15 easy pokeymon points for this one I guess. – 15ee8f99-57ff-4f92-890c-b56153 Nov 30 '17 at 21:14
  • To learn about creating, using, handling C# events go here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/ – Kevin Nov 30 '17 at 21:18

1 Answers1

0

You're just missing the arrow operator (=>) to let C# compiler know that what follows after the (sender, args) is a function body.

You also need to add semicolon after the last brace to end the compound assignment (+=) statement.

Correct version:

videoDownloader.DownloadProgressChanged += (sender, args) => // note the arrow here
{
    if ((args.ProgressPercentage % 1) == 0)
    {
        Console.WriteLine(args.ProgressPercentage);
    }
}; // note the semicolon here

To learn more about anonymous functions, please visit the relevant Microsoft docs topic: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions

Zdeněk Jelínek
  • 2,611
  • 1
  • 17
  • 23