Home

Using Anonymous Methods in C#

|
|  Updated:  
2018-01-31 12:29:06
C# 2010 All-in-One For Dummies
Explore Book
Buy On Amazon
After you have the gist of using delegates, take a quick look at Microsoft’s first cut at simplifying delegates in C# 2.0 a couple of years ago. To cut out some of the delegate rigamarole, you can use an anonymous method. Anonymous methods are just written in more traditional notation. Although the syntax and a few details are different, the effect is essentially the same whether you use a raw delegate, an anonymous method, or a lambda expression.

An anonymous method creates the delegate instance and the method it “points” to at the same time — right in place, on the fly, tout de suite. Here are the guts of the DoSomethingLengthy() method again, this time rewritten to use an anonymous method (boldfaced):

private void DoSomethingLengthy() // No arguments needed this time.

{

...

for (int i = 0; i < duration; i++)

{

if ((i % updateInterval) == 0)

{

<strong> // Create delegate instance.</strong>

<strong> UpdateProgressCallback anon = delegate() </strong>

<strong> {</strong>

<strong> progressBar1.PerformStep(); // Method ‘pointed’ to</strong>

<strong> };</strong>

<strong> </strong>

if(<strong>anon != null</strong>) <strong>anon()</strong>; // Invoke the delegate.

}

}

}

The code looks like standard delegate instantiations, except that after the = sign, you see the delegate keyword, any parameters to the anonymous method in parentheses (or empty parentheses if none), and the method body. The code that used to be in a separate DoUpdate() method — the method that the delegate “points” to — has moved inside the anonymous method — no more pointing. And this method is utterly nameless. You still need the UpdateProgressCallback delegate type definition, and you’re still invoking a delegate instance, named anon in this example.

Needless to say, this description doesn’t cover everything there is to know about anonymous methods, but it’s a start. Look up the term anonymous method in C# Language Help to see more anonymous method examples in the DelegateExamples program on the website. The best advice is to keep your anonymous methods short.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.