C# Anonymous Methods β Inline Delegates Made Simple
Introduction β Why Use Anonymous Methods in C#?
In modern C# programming, especially in event-driven or delegate-based code, sometimes you need a quick way to define logic without naming the method. This is where anonymous methods shine. They provide a way to create inline methods without declaring them separatelyβideal for one-time-use actions and reducing code clutter.
In this guide, youβll learn:
- What anonymous methods are in C#
- Syntax and usage with delegates and events
- Comparison with lambda expressions
- Real-world use cases and best practices
Core Concept β What Is an Anonymous Method?
An anonymous method is a method without a name, defined using the delegate keyword, and assigned to a delegate variable or passed directly as a delegate parameter.
Syntax:
delegate(int x, int y)
{
return x + y;
};
Code Example β Anonymous Method with Delegate
delegate void Greet(string name);
Greet greetUser = delegate(string name)
{
Console.WriteLine($"Hello, {name}!");
};
greetUser("Alice");
Output:
Hello, Alice!
Explanation:
delegate(string name) { ... }defines an anonymous method.- It’s assigned directly to a delegate variable (
greetUser). - Called like a normal method.
Anonymous Methods vs Named Methods
| Feature | Named Method | Anonymous Method |
|---|---|---|
| Requires a name | Yes | No |
| Reusable | Yes | One-time use |
| Inline declaration | No | Yes |
| Use Case | General-purpose methods | Delegates, callbacks, events |
Anonymous Method with Event Handling
button.Click += delegate(object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
};
Use Case: Event handling in Windows Forms or WPF without writing a separate handler method.
Anonymous Method with Return Value
delegate int Square(int num);
Square sq = delegate(int x)
{
return x * x;
};
Console.WriteLine(sq(5)); // Output: 25
Use Case: Return-based logic inside delegates.
Anonymous Method vs Lambda Expression
// Anonymous Method
delegate(string msg)
{
Console.WriteLine(msg);
};
// Lambda Expression (preferred)
msg => Console.WriteLine(msg);
Best Practice: Prefer lambda expressions for shorter, cleaner syntax in modern C#.
Limitations of Anonymous Methods
- Cannot access
reforoutparameters from outer scope. - Less concise than lambda expressions.
- Cannot be used with
asyncdirectly (use lambdas instead).
Best Practices & Tips
Tip: Use anonymous methods only when neededβfor quick logic inside delegates or events.
Pitfall: Donβt overuse; if logic is long or reused, create a named method.
Best Practice: Replace anonymous methods with lambda expressions (=>) in C# 3.0+ for cleaner syntax.
Real-World Use Cases
- Event handlers in UI frameworks (WinForms, WPF)
- Passing quick logic to LINQ methods (though lambda is preferred)
- οΈ Timer callbacks or background worker actions
- Inline sorting/comparison logic
Summary β Recap & Next Steps
Key Takeaways:
- Anonymous methods let you define inline delegates without names.
- Ideal for one-off event handlers or small delegate-based logic.
- Prefer lambda expressions in modern C# for conciseness.
Real-world relevance: Useful in UI event programming, threading callbacks, and legacy LINQ applications.
FAQ Section
What is the difference between an anonymous method and a lambda expression in C#?
Anonymous methods use delegate syntax, while lambda expressions use =>. Lambdas are more concise and preferred.
Can anonymous methods have parameters?
Yes, they can define and accept parameters just like regular methods.
Can I use async in anonymous methods?
No. Use lambda expressions for async logic.
When should I use an anonymous method over a named method?
Use anonymous methods when logic is short, single-use, and tied closely to an event or delegate.
Are anonymous methods still used today?
Rarely. Since C# 3.0, lambda expressions are more commonly used due to cleaner syntax.
Share Now :
