Understanding C# Anonymous Methods: A Comprehensive Guide

C# Anonymous Methods

What are Anonymous Methods?

  • Definition: Anonymous methods are a feature in C# that allows you to define a method without giving it a name.
  • Usage: They are primarily used for defining inline event handlers or for passing a block of code as a delegate.

Key Concepts

Delegates

  • Definition: A delegate is a type that represents references to methods with a specific parameter list and return type.
  • Example: public delegate void MyDelegate(string message);

Syntax of Anonymous Methods

The syntax involves using the delegate keyword followed by a block of code.

  • Example: MyDelegate del = delegate(string msg) { Console.WriteLine(msg); };

Benefits of Anonymous Methods

  • Conciseness: They allow you to write less code by eliminating the need for a separate method declaration.
  • Encapsulation: They can access the variables in their enclosing scope (closure).

How to Use Anonymous Methods

Example 1: Using Anonymous Methods with Delegates

public delegate void MyDelegate(string message);

class Program {
    static void Main() {
        MyDelegate del = delegate(string msg) {
            Console.WriteLine(msg);
        };
        del("Hello, World!");
    }
}

Example 2: Using with Events

public class Publisher {
    public event MyDelegate Notify;

    public void RaiseEvent(string message) {
        if (Notify != null) {
            Notify(message);
        }
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        pub.Notify += delegate(string msg) {
            Console.WriteLine("Event received: " + msg);
        };
        pub.RaiseEvent("Hello, Events!");
    }
}

Conclusion

  • Anonymous methods provide a powerful way to write inline code for delegates and events, making your C# programming more efficient and expressive.
  • They are especially useful for short, one-off methods where creating a named method would be unnecessary.