Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

Delegates Overview | Features | Examples in C#

 In C#, a delegate is a type that represents references to methods with a particular parameter list and return type. Delegates are used to pass methods as arguments, implement event handling, and define callback methods.

Key Features of Delegates

  1. Type Safety: Delegates are type-safe, which means they ensure that the method signature matches the delegate type.
  2. Encapsulation: Delegates encapsulate method references, allowing methods to be passed around like objects.
  3. Multicast: Delegates can hold references to multiple methods, and when invoked, all methods in the delegate’s invocation list are called.


Basic Syntax

A delegate is declared with a signature that matches the methods it can refer to. Here is the basic syntax for declaring a delegate:

public delegate ReturnType DelegateName(Parameters);
 

Examples of Using Delegates

1. Simple Delegate Example

In this example, we'll create a delegate to represent methods that take an integer and return a string.

using System;

public delegate string IntToStringDelegate(int number);

class Program
{
    static void Main()
    {
        // Instantiate the delegate with a method
        IntToStringDelegate delegateInstance = new IntToStringDelegate(NumberToString);

        // Invoke the delegate
        string result = delegateInstance(42);
        Console.WriteLine(result); // Output: "42"
    }

    // Method that matches the delegate signature
    static string NumberToString(int number)
    {
        return number.ToString();
    }
}
 

Explanation:

  • IntToStringDelegate is a delegate type that can point to any method that takes an int and returns a string.
  • NumberToString is a method that matches the delegate signature.
  • We create an instance of the delegate and assign it to the NumberToString method.
  • We then invoke the delegate, which calls NumberToString and returns the string representation of the number.

2. Delegate as a Method Parameter

Delegates can be used to pass methods as parameters. This is useful for implementing callbacks.

using System;

public delegate void PrintMessageDelegate(string message);

class Program
{
    static void Main()
    {
        // Call the method with a delegate
        ProcessMessage("Hello, World!", PrintMessage);
    }

    // Method that takes a delegate as a parameter
    static void ProcessMessage(string message, PrintMessageDelegate printMessage)
    {
        // Use the delegate to print the message
        printMessage(message);
    }

    // Method that matches the delegate signature
    static void PrintMessage(string message)
    {
        Console.WriteLine(message);
    }
}
 

Explanation:

  • PrintMessageDelegate is a delegate type that can point to methods that take a string and return void.
  • ProcessMessage takes a PrintMessageDelegate as a parameter, allowing different methods to be passed in for processing.
  • PrintMessage is a method that matches the delegate signature and is passed as an argument to ProcessMessage.

3. Multicast Delegates

Delegates can be combined to form a multicast delegate, which calls multiple methods when invoked.

using System;

public delegate void NotifyDelegate(string message);

class Program
{
    static void Main()
    {
        // Create instances of delegate
        NotifyDelegate notify = NotifyUser;
        notify += LogMessage; // Add another method to the delegate
        
        // Invoke the delegate
        notify("Hello, Delegates!");
    }

    // First method in the delegate invocation list
    static void NotifyUser(string message)
    {
        Console.WriteLine("User notified: " + message);
    }

    // Second method in the delegate invocation list
    static void LogMessage(string message)
    {
        Console.WriteLine("Log entry: " + message);
    }
}
 

Explanation:

  • NotifyDelegate can point to methods that take a string and return void.
  • Two methods, NotifyUser and LogMessage, are added to the delegate’s invocation list.
  • When notify is invoked, both NotifyUser and LogMessage are called in order.

Post a Comment

0 Comments