New Features in C# 2.0—Anonymous Methods: What about

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

What about…

…using anonymous methods in my own code?

No problem. Not only can you use anonymous methods when you initialize delegates, but also you can pass a block of code anywhere you might otherwise use a delegate.

…what happens if I reference local variables in my anonymous block?

Good question. This can cause quite a bit of confusion and is a natural trap to fall into, especially if you don’t fully understand the consequences. C# allows local variables to be captured in the scope of the anonymous code block, and then they are accessed when the code block is executed. This can create some odd side effects, such as keeping objects around after they might otherwise have been collected. …what about removing the handler for an event that I added with an anonymous delegate; how do I do that?

If you add an event handler with an anonymous delegate, you cannot remove it; therefore, I strongly recommend that you use anonymous delegates only for event handlers you expect to keep permanently attached.

You can use anonymous delegates for other requirements, such as implementing a List.Find method that takes, for example, a delegate describing the search criteria.


Previous_Page_.gif Next_Page_.gif


Personal tools