13.1. C#

The C# language has always been at the forefront of language innovation, with a focus on writing efficient code. It includes features such as anonymous methods, iterators, automatic properties, and static classes that help tidy up your code and make it more efficient.

13.1.1. Anonymous Methods

Anonymous methods are essentially methods that do not have a name, and at surface level they appear and behave the same way as normal methods. A common use for an anonymous method is writing event handlers. Instead of declaring a method and adding a new delegate instance to the event, this can be condensed into a single statement, with the anonymous method appearing inline. This is illustrated in the following example:

private void Form1_Load(object sender, EventArgs e)
{
    this.button1.Click += new EventHandler(OldStyleEventHandler);

    this.button1.Click += delegate{
                            Console.WriteLine("Button pressed - new school!");
                                   };
}
private void OldStyleEventHandler(object sender, EventArgs e){
    Console.WriteLine("Button pressed - old school!");
}

The true power of anonymous methods is that they can reference variables declared in the method in which the anonymous method appears. The following example searches a list of employees, as you did in the previous chapter, for all employees who have salaries less than $40,000. The difference here is that instead of defining this threshold in the predicate method, the amount is held in a method variable. This dramatically reduces the amount of code you ...

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.