C# 7.0 All-in-One For Dummies
Book image
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 authors:

John Paul Mueller is a writer on programming topics like AWS, Python, Java, HTML, CSS, and JavaScript. William Sempf is a programmer and .NET evangelist. Chuck Sphar was a full-time senior technical writer for the Visual C++ product group at Microsoft.

This article can be found in the category: