Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
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.
Liked By
Write Answer
What are delegates and their uses? Also, give an example.
Join MindStick Community
You have need login or register for voting of answers or question.
Sanjay Goenka
19-Apr-2023In 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.