How to Create and Use Anonymous Delegates in C# (C Sharp) What
are Anonymous Delegates? In general, delegates are used to wrap methods and calling a delegate will in turn call the method wrapped inside the delegate. In most of the cases, method wrapped by the delegate will already be defined.
What if you want to define a method only at the time of wrapping it inside the delegate? Does that mean creating an anonymous method without any name? Yes it is. Is it possible in C#? It wasnt possible in the earlier versions of C#. However C# version 2.0 and above supports anonymous methods and calls them using delegates. Such delegates are termed as anonymous delegates. This article will help you in understanding the creation and usage of anonymous delegates in C#. Anonymous Methods Vs Named Methods: To have a
better idea on anonymous delegates, consider the following example: public static
void Main( ) { Output of
this code will be: This example has a delegate called testDelegate. You are creating an instance of this delegate and using the same instance for two purposes: To
create and execute an anonymous method If you have to wrap a named method called testValidMethod inside the delegate testDelegate using its instance dele1, all that you have to do is: dele1 = new
testDelegate(testValidMethod); When you
are creating an anonymous delegate, coding is different. You have to use: Instead of the instance operator new followed by the delegate name, you have to use delegate( ) followed by the anonymous method definition inside { } braces. Do not forget to place a semicolon ; after the closing brace }. When Do You Use Anonymous Method Instead of Named Method? In the above example, testValidMethod is used only once in the entire coding and that usage is inside a delegate. In this case, creating testValidMethod separately and using it inside the delegate has a considerable overhead. This overhead is avoided when you remove the function testValidMethod and place its code inside an anonymous delegate. Anonymous Delegate with Parameters: Example above deals with a delegate that doesnt have parameters. Can anonymous delegates be defined with parameters? Yes. Consider the following example which uses a named method inside a delegate with parameters: public delegate
void testDelegate(String param); This block
of code can be altered as shown below to make use of anonymous method
instead of the named method testValidMethod: Anonymous
methods can also access variables defined in the method inside which anonymous
delegate is created. Even the class members (of the class inside which
anonymous method is created) can be accessed inside anonymous method.
Here is an example: class testDelegateClass
{ Restrictions
in Using Anonymous Delegate:
|