In C#, a delegate is a type that represents a method signature. Delegates allow you to treat methods as objects, which can be passed as arguments to other methods or stored as variables. Delegates provide a way to implement the observer pattern and to write callback functions.
public delegate void MyDelegate(string message);
public class MyClass
{
public void MethodA(string message)
{
Console.WriteLine($"MethodA: {message}");
}
public void MethodB(string message)
{
Console.WriteLine($"MethodB: {message}");
}
}
public class Program
{
public static void Main()
{
MyClass obj = new MyClass();
MyDelegate del1 = new MyDelegate(obj.MethodA);
MyDelegate del2 = new MyDelegate(obj.MethodB);
// Call the delegate with different messages
del1("Hello");
del2("World");
}
}
In this example, we define a delegate named "MyDelegate" that takes a single string parameter and returns void. We also define a class "MyClass" that contains two methods, "MethodA" and "MethodB", that match the signature of the delegate.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, a delegate is a type that represents a method signature. Delegates allow you to treat methods as objects, which can be passed as arguments to other methods or stored as variables. Delegates provide a way to implement the observer pattern and to write callback functions.
In this example, we define a delegate named "MyDelegate" that takes a single string parameter and returns void. We also define a class "MyClass" that contains two methods, "MethodA" and "MethodB", that match the signature of the delegate.