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 } }
0 Comments