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.