Anonymous Delegates Sample

This sample demonstrates how to use an anonymous method to calculate a salary bonus for an employee. An anonymous method simplifies the program because you do not have to define a separate method.

Note

This sample is misnamed. The correct term for this feature is anonymous methods. Furthermore, anonymous methods are a feature of C# 2.0 and have been mostly superseded in C# 3.0 by lambda expressions. For more information about anonymous methods and lambda expressions, see Anonymous Functions (C# Programming Guide).

The data for each employee is stored in an object that contains personal details and a delegate that references the algorithm required to calculate the bonus. By using a delegate to define the algorithm, the same method can be used to perform the bonus calculation, regardless of how it is actually calculated. Also of note, a local variable, multiplier, becomes a captured outer variable because it is referenced in a delegated calculation.

To get samples and instructions for installing them

  • Do one or more of the following:

    • On the Help menu, click Samples.

      The Readme displays information about samples.

    • Visit the Visual Studio 2008 Samples Web site. The most recent versions of samples are available there.

    • Locate samples on the computer on which Visual Studio is installed. By default, samples and a Readme file are installed in drive:\Program Files\Microsoft Visual Studio 9.0\Samples\lcid. For Express editions of Visual Studio, all samples are located online.

For more information, see Visual Studio Samples.

Security noteSecurity Note:

This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties.

To build and run the AnonymousDelegates Code sample within Visual Studio

  • On the Debug menu, click Start Without Debugging.

To build and run the AnonymousDelegates Code sample from the Command Line

  1. Use the Change Directory (cd) command to change to the AnonymousDelegates directory.

  2. Type the following:

    csc AnonymousDelegates.cs
    AnonymousDelegates
    

See Also

Concepts

Visual C# Samples

Reference

Anonymous Methods (C# Programming Guide)

Delegates (C# Programming Guide)

Other Resources

C# Reference

Change History

Date

History

Reason

July 2008

Added note to introduction.

Content bug fix.