Anonymous Methods in C#
Table of Content:
What is anonymous methods?
In C#, anonymous methods provide a way to create inline methods without explicitly naming them. They were introduced in C# 2.0 and serve as a way to implement delegates. Anonymous methods are closely related to lambda expressions (introduced in C# 3.0), as both offer a way to create short, unnamed methods. However, anonymous methods have a slightly different syntax.
When to Use Anonymous Methods
- Event Handling: When you need to attach a small piece of code to an event handler.
- Delegate Invocation: When you need a short, simple method to be passed to a delegate and don't want to define a separate method.
- Quick Prototyping: When you're writing quick and temporary logic that won't be reused.
Features of Anonymous Methods
- No Explicit Name: As the name suggests, anonymous methods do not have a name. They are defined at the point where they are needed.
- Can Capture Variables: Like lambda expressions, anonymous methods can capture and use local variables defined in the scope where they are created.
- Used with Delegates: Anonymous methods are primarily used with delegates. This is a way to pass a block of code to a delegate without needing to define a separate method.
Syntax of Anonymous Methods
An anonymous method is created using the delegate keyword, followed by a code block:
delegate (parameters) { // method body };
Here’s the basic form:
delegate (parameters) { // code };
Example of an Anonymous Method
Let’s look at an example where an anonymous method is assigned to a delegate:
using System; public class Program { public delegate void PrintDelegate(string message); public static void Main() { // Assign an anonymous method to the delegate PrintDelegate print = delegate (string message) { Console.WriteLine(message); }; // Call the delegate print("Hello from an anonymous method!"); // Output: Hello from an anonymous method! } }
In this example:
- The
delegate (string message)is the anonymous method. - It is assigned to a delegate
PrintDelegate. - The method is called using the delegate and prints the provided message.
Example of an Anonymous Method - Without Parameters
using System; namespace RummanAnsari_ConsoleApp1 { internal class Program { public delegate void PrintDelegate(); static void Main(string[] args) { // Assign an anonymous method to the delegate PrintDelegate printRA = delegate () { Console.WriteLine("Inside anonymous method"); }; // Call the delegate printRA(); // Output: Hello from an anonymous method! } } }
Anonymous Method Example with Parameters
Here’s an example of an anonymous method with parameters:
using System; public class Program { public delegate int Calculate(int x, int y); public static void Main() { // Anonymous method to add two numbers Calculate add = delegate (int x, int y) { return x + y; }; Console.WriteLine(add(5, 3)); // Output: 8 } }
In this example:
- An anonymous method is assigned to the
Calculatedelegate. - The anonymous method takes two integer parameters
xandy, adds them, and returns the result.
Capturing Outer Variables (Closures)
Anonymous methods can capture outer variables, meaning they can access variables from the method in which they are defined.
using System; public class Program { public delegate void PrintDelegate(); public static void Main() { int outerVariable = 10; // Anonymous method capturing outerVariable PrintDelegate print = delegate { Console.WriteLine("Outer variable value: " + outerVariable); }; // Call the delegate print(); // Output: Outer variable value: 10 } }
In this example:
- The anonymous method captures the
outerVariablefrom the outer method scope. - When the delegate
printis invoked, it prints the value of the captured variable.
Anonymous Methods vs Lambda Expressions
Here’s a comparison table highlighting the key differences between Anonymous Methods and Lambda Expressions in C#:
| Feature | Anonymous Methods | Lambda Expressions |
|---|---|---|
| Syntax | Uses delegate keyword. |
Uses the => syntax (arrow function). |
| Introduced in | C# 2.0 | C# 3.0 |
| Parameter Declaration | Parameter types can be specified explicitly. | Typically omits parameter types (inferred from context). |
| Return Type | Can explicitly define a return type. | The return type is inferred automatically. |
| Conciseness | Longer syntax, requires delegate and full method body. |
More concise, cleaner, and easier to read. |
| Capturing Variables | Can capture variables from the enclosing scope (closures). | Can capture variables from the enclosing scope (closures). |
| Use in Events/Delegates | Often used in event handling and with delegates. | Also used in event handling and delegates, but with cleaner syntax. |
| Handling Multiple Statements | Requires curly braces { } for multiple statements. |
Requires curly braces { } for multiple statements. |
| Readability | Slightly verbose for short tasks. | More readable, especially for short and simple expressions. |
| Parameter Parentheses | Parentheses required when specifying parameter types. | Parentheses optional for a single parameter without type declaration. |
| Explicit Anonymous Method Block | Requires delegate keyword followed by a block of code. |
Short syntax, uses => for expression or block of code. |
| Support for Expression Bodies | No support for expression bodies. | Supports expression bodies for single-line expressions. |
| Return Keyword | Explicit return required for non-void methods. |
Implicit return for single-line lambda expressions (no return keyword needed). |
Example of Each:
Anonymous Method:
Func square = delegate(int x) { return x * x; };
Lambda Expression:
Func square = x => x * x;
Key Points:
- Anonymous methods are more verbose but allow explicit parameter types and more flexibility in declaring multi-line methods.
- Lambda expressions are cleaner, easier to read, and typically preferred for their conciseness and modern syntax.
Conclusion
- Anonymous methods in C# allow you to write quick, inline methods without having to give them a name.
- They are typically used with delegates, event handlers, and other scenarios where a full method definition may not be necessary.
- While anonymous methods are still useful, lambda expressions are often preferred today for their simplicity and conciseness.