π§ 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
ref
orout
parameters from outer scope. - Less concise than lambda expressions.
- Cannot be used with
async
directly (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 :