C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Anonymous Delegate

In this tutorial, we'll demonstrate how to use anonymous delegates in C#. Anonymous delegates are an older feature, introduced in C# 2.0, which allows you to create delegate instances without explicitly defining a named method. However, in C# 3.0, lambda expressions were introduced, which are a more concise and powerful way to define anonymous methods. It is recommended to use lambda expressions in most cases.

  • Set up the environment

Create a new C# Console Application project in Visual Studio.

  • Define a delegate

First, define a delegate type named MyDelegate that takes two integers as parameters and returns an integer:

delegate int MyDelegate(int a, int b);
  • Create an anonymous delegate

Now, create an anonymous delegate that takes two integers, adds them together, and returns the result:

MyDelegate add = delegate(int a, int b)
{
    return a + b;
};
  • Use the anonymous delegate

In the Main method, use the anonymous delegate to add two numbers together and display the result:

static void Main(string[] args)
{
    MyDelegate add = delegate(int a, int b)
    {
        return a + b;
    };

    int result = add(5, 7);
    Console.WriteLine($"Result: {result}");
    Console.ReadLine();
}

When you run the Console Application, you should see the message "Result: 12" displayed in the console.

  • Compare with a lambda expression

In C# 3.0 and later, you can use lambda expressions instead of anonymous delegates. Here's the same example using a lambda expression:

MyDelegate addLambda = (a, b) => a + b;

int resultLambda = addLambda(5, 7);
Console.WriteLine($"Result (using lambda): {resultLambda}");

Lambda expressions provide a more concise and flexible syntax compared to anonymous delegates. In most cases, it's recommended to use lambda expressions over anonymous delegates.

In this tutorial, we've shown you how to use anonymous delegates in C#. Anonymous delegates provide a way to create delegate instances without explicitly defining a named method, but they have been largely superseded by lambda expressions, which offer a more concise and powerful syntax.

  1. C# anonymous delegate example:

    • Description: This example introduces the concept of anonymous delegates in C#, showcasing a simple use case where an anonymous delegate is used to perform a specific action.
    • Code:
      // Declare and use an anonymous delegate
      Action<int, int> addDelegate = delegate(int a, int b)
      {
          Console.WriteLine($"Sum: {a + b}");
      };
      
      // Invoke the anonymous delegate
      addDelegate(3, 5);
      
  2. Anonymous delegate parameters in C#:

    • Description: Focusing on the parameters of anonymous delegates, this example demonstrates how to define and use parameters within an anonymous delegate.
    • Code:
      // Declare and use an anonymous delegate with parameters
      Action<int, int> multiplyDelegate = delegate(int x, int y)
      {
          Console.WriteLine($"Product: {x * y}");
      };
      
      // Invoke the anonymous delegate with parameters
      multiplyDelegate(4, 6);
      
  3. C# anonymous delegate return value:

    • Description: Illustrating how to use anonymous delegates with return values, this example shows a delegate that calculates and returns the sum of two numbers.
    • Code:
      // Declare and use an anonymous delegate with a return value
      Func<int, int, int> sumDelegate = delegate(int a, int b)
      {
          return a + b;
      };
      
      // Invoke the anonymous delegate and print the result
      Console.WriteLine($"Sum: {sumDelegate(7, 8)}");
      
  4. Working with anonymous delegates in event handlers:

    • Description: This example demonstrates the use of anonymous delegates as event handlers, showcasing their flexibility in responding to events.
    • Code:
      // Declare an event with an anonymous delegate as the handler
      public event Action<string> MyEvent = delegate(string message)
      {
          Console.WriteLine($"Event handled: {message}");
      };
      
      // Raise the event
      MyEvent("Hello, world!");
      
  5. Delegates and anonymous methods in C#:

    • Description: Providing an overview of delegates and anonymous methods, this example shows how anonymous methods can be used as delegates for concise function definitions.
    • Code:
      // Declare a delegate with an anonymous method
      Action<int> printDelegate = delegate(int number)
      {
          Console.WriteLine($"Number: {number}");
      };
      
      // Invoke the delegate with an anonymous method
      printDelegate(10);