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 wasn’t 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 delegate void testDelegate( );
class testDelegateClass {
public static void testValidMethod( ) {
Console.WriteLine(“Executing testValidMethod Using Delegate”);
}

public static void Main( ) {
//Creation of Anonymous Delegate
testDelegate dele1 = delegate( ) {
Console.WriteLine(“Executing Anonymous Method Using Delegate”);
};
//Calling Anonymous Delegate
dele1( );
// Wrapping a normal method using the same delegate instance
dele1 = new testDelegate(testValidMethod);
dele1( );
}
}

Output of this code will be:
Executing Anonymous Method Using Delegate
Executing testValidMethod Using Delegate

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
• To execute a method that is already defined

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);
Now when you call dele1( ), code inside testValidMethod will be executed.

When you are creating an anonymous delegate, coding is different. You have to use:
delegateName delegateObj = delegate( ) {/* anonymous method definition */};

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 doesn’t 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);
class testDelegateClass {
public void testValidMethod(String param ) {
Console.WriteLine(param);
}
public static void Main( ) {
testDelegate dele1 = new testDelegate(testValidMethod);
dele1(“Executing testValidMethod Using Delegate”);
}
}

This block of code can be altered as shown below to make use of anonymous method instead of the named method testValidMethod:
public delegate void testDelegate(String param);
class testDelegateClass {
public static void Main( ) {
testDelegate dele1= delegate(String param){
Console.WriteLine(param);
};
dele1(“Executing Anonymous Method Using Delegate”);
}
}

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:
public delegate void testDelegate( );

class testDelegateClass {
public static void Main( ) {
String param = “ Executing Anonymous Method Using Delegate”;
testDelegate dele1= delegate( ){
Console.WriteLine(param);
};
dele1( );
}
}

Restrictions in Using Anonymous Delegate:

• Variables defined inside anonymous method have its scope restricted to that method alone. Those variables cannot be accessed outside the anonymous method

• If you use goto or break or continue statements inside your anonymous method, then the target of those statements should be within the anonymous method and not outside. Similarly such statements used outside the anonymous method should not point to a code inside the method

• Parameters such as ref or out defined outside the anonymous method cannot be accessed from inside

• Unsafe Code cannot be accessed inside anonymous method

|Designing applications in .Net using Service Oriented Architecture | How to Create and Use Anonymous Delegates in C# (C Sharp) |How to Define Custom Attributes in C# (C Sharp)| How To Handle Errors While Developing ASP.NET Applications | How to Use Indexer in Classes and Interfaces of C# (C Sharp)| Illustration of Access Keywords (base, this) with Examples in C# (C Sharp) | Illustration of Null Coalesce Operator (??) in C# (C Sharp) |Indexers Vs Properties in C# (C Sharp) | More about Reserved Attributes of C# (C Sharp)| Overview of Unified Type System of C# (C Sharp) | Purpose of Delegates in C# (C Sharp) |How does Simple Object Access Protocol (SOAP) help in Internet Communication |How to Create and Use Anonymous Delegates in C# (C Sharp)|


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.