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# Delegate

In C#, a delegate is a reference type that represents a method with a specific signature. Delegates allow you to pass methods as arguments to other methods and create events. In this tutorial, we'll cover the basics of delegates, anonymous methods, and lambda expressions.

  • Basic Delegate Definition and Usage:

To create a delegate, you need to declare it with the delegate keyword, followed by a method signature.

public delegate void MyDelegate(string message);

This delegate represents a method that takes a string parameter and returns void. To use the delegate, create a method with the same signature:

public static void ShowMessage(string message)
{
    Console.WriteLine("Message: " + message);
}

Now, you can create an instance of the delegate, and assign the method to it:

MyDelegate myDelegate = new MyDelegate(ShowMessage);

To invoke the delegate, use the following syntax:

myDelegate("Hello, World!");
  • Multicast Delegates:

Delegates can hold references to multiple methods. You can add methods to a delegate using the += operator:

public static void ShowAnotherMessage(string message)
{
    Console.WriteLine("Another Message: " + message);
}

myDelegate += ShowAnotherMessage;

When you invoke the delegate, it will call all the methods in the order they were added:

myDelegate("Hello, World!"); // Calls both ShowMessage and ShowAnotherMessage
  • Anonymous Methods:

You can create a delegate instance without defining a separate method using an anonymous method:

MyDelegate myDelegate = delegate(string message)
{
    Console.WriteLine("Anonymous Message: " + message);
};
  • Lambda Expressions:

C# also allows you to create delegates using lambda expressions, which provide a more concise way to define anonymous methods:

MyDelegate myDelegate = message => Console.WriteLine("Lambda Message: " + message);

Lambda expressions can have multiple statements enclosed in a block:

MyDelegate myDelegate = message =>
{
    Console.WriteLine("Lambda Message:");
    Console.WriteLine(message);
};

Here's a complete example using delegates, anonymous methods, and lambda expressions:

using System;

namespace DelegateTutorial
{
    public delegate void MyDelegate(string message);

    class Program
    {
        public static void ShowMessage(string message)
        {
            Console.WriteLine("Message: " + message);
        }

        public static void ShowAnotherMessage(string message)
        {
            Console.WriteLine("Another Message: " + message);
        }

        static void Main(string[] args)
        {
            // Regular method
            MyDelegate myDelegate = new MyDelegate(ShowMessage);
            myDelegate += ShowAnotherMessage;

            // Anonymous method
            myDelegate += delegate(string message)
            {
                Console.WriteLine("Anonymous Message: " + message);
            };

            // Lambda expression
            myDelegate += message => Console.WriteLine("Lambda Message: " + message);

            // Invoking the delegate
            myDelegate("Hello, World!");
        }
    }
}

This example demonstrates the different ways you can create and use delegates in C#.

  1. C# delegate example:

    • Description: A delegate in C# is a type that represents references to methods. It provides a way to encapsulate a method, similar to function pointers in C and C++.
    • Code:
      // Declare a delegate
      public delegate void MyDelegate(string message);
      
      // Use the delegate
      MyDelegate myDelegate = Console.WriteLine;
      myDelegate("Hello, delegates!");
      
  2. How to declare and use delegates in C#:

    • Description: Declaring and using delegates involves specifying the delegate signature and assigning methods to it.
    • Code:
      // Declare a delegate
      public delegate void MyDelegate(string message);
      
      // Use the delegate
      MyDelegate myDelegate = Console.WriteLine;
      myDelegate("Hello, delegates!");
      
  3. Multicast delegates in C#:

    • Description: Multicast delegates can reference multiple methods, and invoking the delegate invokes all the methods it references.
    • Code:
      // Multicast delegate
      MyDelegate multiDelegate = Console.WriteLine;
      multiDelegate += s => Console.WriteLine($"Second delegate: {s}");
      multiDelegate("Multicast delegates!");
      
  4. Using anonymous delegates in C#:

    • Description: Anonymous delegates allow you to define a method inline without explicitly declaring a separate method.
    • Code:
      MyDelegate anonymousDelegate = delegate (string message)
      {
          Console.WriteLine($"Anonymous delegate: {message}");
      };
      anonymousDelegate("Hello, anonymous delegates!");
      
  5. Delegate chaining in C#:

    • Description: Chaining delegates involves combining multiple delegates, and invoking one delegate invokes all delegates in the chain.
    • Code:
      MyDelegate firstDelegate = s => Console.WriteLine($"First delegate: {s}");
      MyDelegate secondDelegate = s => Console.WriteLine($"Second delegate: {s}");
      
      MyDelegate chainedDelegate = firstDelegate + secondDelegate;
      chainedDelegate("Delegate chaining!");
      
  6. Action and Func delegates in C#:

    • Description: Action and Func are generic delegates that simplify working with delegates for methods with specific signatures.
    • Code:
      Action<string> actionDelegate = Console.WriteLine;
      actionDelegate("Hello, Action!");
      
      Func<int, int, int> addDelegate = (a, b) => a + b;
      int result = addDelegate(3, 5);
      
  7. Events and delegates in C#:

    • Description: Events in C# are a special kind of multicast delegate used to implement the observer pattern. They provide a standardized way for classes to communicate.
    • Code:
      public class Publisher
      {
          // Declare an event
          public event MyDelegate MyEvent;
      
          // Raise the event
          public void RaiseEvent(string message)
          {
              MyEvent?.Invoke(message);
          }
      }
      
      // Subscribe to the event
      Publisher publisher = new Publisher();
      publisher.MyEvent += s => Console.WriteLine($"Event handled: {s}");