Skip to Main Content
Professional Visual Studio® 2008
book

Professional Visual Studio® 2008

by Nick Randolph, David Gardner
July 2008
Intermediate to advanced content levelIntermediate to advanced
1026 pages
27h 59m
English
Wrox
Content preview from Professional Visual Studio® 2008

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional Visual Studio® 2010

Professional Visual Studio® 2010

Nick Randolph, David Gardner, Michael Minutillo, Chris Anderson

Publisher Resources

ISBN: 9780470229880Purchase book