What is a Delegate in C#, and What Are the Types of Delegates Available?

A delegate in C# is a type that represents references to methods with a specific parameter list and return type. You can think of a delegate as a pointer to a function.

It allows methods to be passed as arguments to other methods and can be used to define callback methods or event handlers. 

Delegates are particularly useful for implementing events and callback methods.

Delegates are type-safe, meaning the method(s) it refers to must match the signature defined by the delegate. This ensures that the method you’re calling through the delegate is compatible with what you expect. 

A delegate can point to more than one method. When you invoke a multicast delegate, all the methods it points to are called in order.

Types of Delegates in C#:

Single-Cast Delegates:

A single-cast delegate points to one method. This is the simplest form of a delegate.

Example:

public delegate void SimpleDelegate(string message);

public class Program
{
    public static void DisplayMessage(string message)
    {
        Console.WriteLine(message);
    }

    public static void Main()
    {
        SimpleDelegate del = new SimpleDelegate(DisplayMessage);
        del("Hello, World!");  // Calls DisplayMessage method
    }
}
    


Multicast Delegates: 

A multicast delegate can point to multiple methods. When invoked, it will call all the methods in its list, in the order they were added. 

Example:

public delegate void MultiDelegate(string message);

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

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

    public static void Main()
    {
        MultiDelegate del = new MultiDelegate(DisplayMessage);
        del += LogMessage;  // Adding another method to the delegate

        del("Hello, World!");   // Calls both DisplayMessage and LogMessage
    }
}  


Func Delegates:

Func delegates are predefined generic delegates in C# that can return a value. They can have zero or more input parameters, but they always return a value. It can take up to 16 parameters and returns a value.

Example:

Func<int, int, int> add = (a, b) => a + b;
int result = add(3, 4);  // Returns 7

Action Delegates:

Action delegates are also predefined generic delegates, but they do not return a value (they return void). They can have zero or more input parameters.

Example:

Action<string> greet = name => Console.WriteLine("Hello, " + name);
greet("Kumar");  // Prints "Hello, Kumar"

Predicate Delegates:

Predicate is another predefined delegate that represents a method that takes a single parameter and returns a bool value. It’s commonly used for filtering or searching operations.

Example:

Predicate<int> isPositive = num => num > 0;
bool result = isPositive(5);  // Returns true

Post a Comment

0 Comments