7️⃣ C# Methods & Functions
Estimated reading: 3 minutes 28 views

🧠 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

FeatureNamed MethodAnonymous Method
Requires a nameβœ… Yes❌ No
Reusableβœ… Yes❌ One-time use
Inline declaration❌ Noβœ… Yes
Use CaseGeneral-purpose methodsDelegates, 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 or out 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧠 C# Anonymous Methods

Or Copy Link

CONTENTS
Scroll to Top