C# Anonymous Methods
A method without a name is known as an anonymous method, and it was first introduced in C# 2.0. It is helpful when a user wishes to build an inline method and send parameters to the anonymous method like other methods. The delegate keyword defines an anonymous method, which the user can then assign to a variable of the delegate type.
Syntax:
delegate(parameter_list){
// Code.
};
Example:
The CODE for the following program is as follows:
using System;
class Preethi {
public delegate void petanim(string pet);
// Main method
static public void Main()
{
// An anonymous method with one parameter
petanim p = delegate(string mypet)
{
Console.WriteLine("My favorite pet is: {0}",
my pet);
};
p("Dog");
}
}
OUTPUT:
The Output for the following program will be:
![C# Anonymous Methods](https://static.tutorialandexample.com/csharp/csharp-anonymous-methods1.png)
- Inline delegate is another name for this technique.
- You can build a delegate object using this method without adding additional methods.
- The outer method's variables are accessible from this method. These variables fall under the category of outside variables.
- The favorite is the outside variable, as demonstrated in the example below.
Example:
The CODE for the following program is as follows:
using System;
class Preethi {
// Create a delegate
public delegate void petanim(string pet);
// Main method
static public void Main()
{
string fav = "Rabbit";
// Anonymous method with one parameter
petanim p = delegate(string mypet)
{
Console.WriteLine("My favorite pet is {0}.",
my pet);
// Accessing variable defined
// outside the anonymous function
Console.WriteLine("And I like {0} also.", fav);
};
p("Dog");
}
}
OUTPUT:
The Output for the following program is as follows:
![C# Anonymous Methods](https://static.tutorialandexample.com/csharp/csharp-anonymous-methods2.png)
Another method that accepts delegate as a parameter can receive this method as a parameter. You can remove the parameter list from anonymous methods, which enables you to turn an anonymous method into a delegate.
- Anonymous methods do not support jump statements like goo, break, and continue.
- The anonymous method block indicates the scope of the parameters in the anonymous method.
- Unsafe code is not accessed by an anonymous method.
- An anonymous method cannot access the outer scopes in, ref, and out parameters.
- To the left of the operator, an anonymous method cannot be used.
- A method that is anonymous can also serve as an event handler.
An anonymous method is, as its name suggests, a method without a name.
Example:
The CODE for the following program is as follows:
public delegate void Print(int value);
static void Main(string[] args)
{
Print print = delegate(int val) {
Console.WriteLine("Inside Anonymous method. Value: {0}", val);
};
print(100);
}
OUTPUT:
The Output for the following program is as follows:
Inside Anonymous method. Value: 100
Example:
The CODE for the following program is as follows:
public delegate void Print(int value);
static void Main(string[] args)
{
int i = 10;
Print prnt = delegate(int val) {
val += i;
Console.WriteLine("Anonymous method: {0}", val);
};
prnt(100);
}
OUTPUT:
The Output for the following program is as follows:
Anonymous method: 110
Anonymous Method Limitations:
- Statements that leap, such as goto, break, or continue, are not permitted.
- An outer method's ref or out argument cannot be accessed.
- It can't access or have any unsafe code.
- It is not permitted to utilize it after the operator is on the left.
With anonymous methods, inline code blocks can be defined in C# without explicitly declaring a named method. They are a vital feature that enables programmers to define code blocks immediately at the place of use, allowing them to write straightforward and adaptable code. In this tutorial, the specifics of anonymous methods in C# will be discussed, along with usage examples and benefits.
Syntax:
The delegate keyword, an optional argument list, an arrow (=>) token, and a code block make up the syntax of an anonymous method. The parameters that the anonymous method can accept are listed in the parameter list if one is provided. The method's actual implementation is contained in the code block.
delegate (parameters)
{
// Code block
};
Using Scenarios:
1. Event Handlers: Anonymous methods are frequently employed as event handlers. You can create the event handler inline, directly at the point of subscription, as opposed to defining separate named methods for each event. By grouping comparable code, this method eliminates the necessity for additional method declarations and enhances code readability.
button.Click += delegate (object sender, EventArgs e)
{
// Event handler code
};
2. Callback Functions: Anonymous methods are helpful when interacting with callback functions. For instance, rather than defining distinct named methods for the callback logic when utilizing asynchronous activities or calling other APIs. This aids in keeping a clean, simple code structure.
asyncOperation.Start(callback: delegate (string result)
{
// Callback logic
});
3. LINQ Queries: Data can be accessed from various sources, including collections, databases, and XML, using LINQ (Language Integrated Query). LINQ expressions frequently employ anonymous methods to specify unique ordering, filtering, and projection logic.
var filteredItems = items.Where(delegate (Item item)
{
// Filtering logic
return item.Price > 100;
});
Benefits:
1. Readability and Maintainability: Developers can write code inline, near the point of use, using anonymous methods, which improves the readability and maintainability of the code. It does away with the requirement for dispersed named methods, resulting in smaller and more self-contained code.
2. Encapsulation: Variables in the enclosing scope are accessible to anonymous methods. Closure, which increases code modularity and eliminates the need for global variables, enables you to encapsulate related data inside the anonymous procedure.
3. Conciseness: Anonymous methods lessen the verbosity of the code by eliminating the requirement to declare named methods separately. Code becomes shorter and more expressive as a result, which makes it simpler to comprehend and debug.
4. Flexibility: The ability to construct ad hoc code blocks with unique logic suited to specific contexts is made possible by anonymous methods. They are accommodating when creating distinct named methods would be tedious or superfluous.
Limitations:
While anonymous methods have many benefits, there are some drawbacks to be aware of:
1. Lack of Reusability: Because anonymous methods are defined inline, the codebase cannot use them more than once. Using named methods or lambda expressions is preferable if you reuse the same logic across several contexts.
2. Limited Functionality: Anonymous methods cannot be explicitly assigned to variables or utilized as return values. It would help if you thought about utilizing lambda expressions or named methods in their place to achieve this behavior.
Conclusion:
As a result, developers can build inline code blocks in C# by using anonymous methods, a strong and clear feature that eliminates the need for distinct named methods. They provide several advantages, such as better code readability, data encapsulation, and adaptability in situations like event handling, callbacks, and LINQ queries. Anonymous methods make code easier to read and maintain by removing the need for sporadic method declarations.
The drawbacks of anonymous methods must be considered, such as their lack of reusability and restricted functionality compared to named methods or lambda expressions. Developers should carefully analyze their use cases and select the best approach based on the needs of their application to make the best use of anonymous methods.
In conclusion, anonymous methods are a valuable tool for C# developers, offering a practical approach to managing inline code blocks and assisting in creating more concise and expressive code. They can significantly improve the overall development process and the codebase's maintainability when used wisely and in conjunction with other language features.
In C#, anonymous methods are a helpful feature that lets you build inline code blocks without declaring individual named methods. They increase the code's adaptability, readability, and maintainability, especially when event management, callbacks, and LINQ queries are included. It's vital to be aware of their limits and to decide which approach will work best for your application depending on its specific requirements.