Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Anonymous Methods in C#

Introduction

In C#, an anonymous method is a method without a name. Anonymous methods are useful when you need to encapsulate a code block and pass it as a delegate parameter without having to explicitly define a separate method. They were introduced in C# 2.0 and provide a way to write inline code for delegate instances.

Creating Anonymous Methods

Anonymous methods are created using the delegate keyword. The syntax for creating an anonymous method is shown in the example below:

delegate (parameters) {
    // Code block
};
                

Let's see a simple example of an anonymous method:

using System;

namespace AnonymousMethodExample
{
    class Program
    {
        delegate void PrintDelegate(string message);

        static void Main(string[] args)
        {
            PrintDelegate print = delegate (string message) {
                Console.WriteLine(message);
            };

            print("Hello, World!");
        }
    }
}
                
Output:
Hello, World!

Using Anonymous Methods with Events

Anonymous methods can also be used to handle events. Events in C# are based on delegates, and anonymous methods provide a convenient way to create event handlers without explicitly defining a separate method.

Here is an example of using anonymous methods with events:

using System;

namespace AnonymousMethodEventExample
{
    class Program
    {
        public delegate void Notify();  // delegate

        public class ProcessBusinessLogic
        {
            public event Notify ProcessCompleted; // event

            public void StartProcess()
            {
                Console.WriteLine("Process Started!");
                // some code here..
                OnProcessCompleted();
            }

            protected virtual void OnProcessCompleted()
            {
                ProcessCompleted?.Invoke();
            }
        }

        static void Main(string[] args)
        {
            ProcessBusinessLogic bl = new ProcessBusinessLogic();
            bl.ProcessCompleted += delegate {
                Console.WriteLine("Process Completed!");
            };

            bl.StartProcess();
        }
    }
}
                
Output:
Process Started!
Process Completed!

Advantages of Anonymous Methods

Anonymous methods provide several benefits:

  • Inline Code: You can write the code directly where it is needed, improving readability for short sections of code.
  • Closure: Anonymous methods can access variables in the scope where they are defined, making it easier to work with local variables.
  • Event Handlers: They simplify the creation of event handlers, especially for simple events.

Limitations of Anonymous Methods

While anonymous methods are powerful, they do have some limitations:

  • Readability: For complex logic, anonymous methods can make the code harder to read and maintain.
  • Debugging: Debugging anonymous methods can be more challenging compared to named methods.

Conclusion

Anonymous methods in C# provide a powerful way to write inline code for delegates and event handlers. They improve code readability for small tasks and allow for easy access to local variables. However, for more complex logic, named methods might be more appropriate for maintainability and debugging purposes.