Delegates in C# refer to a type that is used to represent the reference to the methods with a specific parameter list and return type. It allows us to safely encapsulate a method which is similar to a function pointer in other languages.
Delegates are very useful when you need to handle the events and callbacks as even handlers are nothing than the methods that are invoked via delegates.
In this tutorial, we will explore the fundamentals of working with delegates in C# for callbacks.
Delegate Definition
In C#, we can define a delegate using the “delegate” keyword and a function signature as shown in the example syntax as follows:
In this case, we define a delegate called “Del” that can encapsulate any method that takes two <T> values as parameters and returns an <RT> type.
Using Delegates
Once we define a delegate, we can then create an instance of the delegate and associate it with a specific method that matches the delegate signature.
Take the following example delegate definition and usage:
In the given example, we start by defining a “Calculator” class with a method called “Add”.
We then create a delegate type called “Del” that matches the signature of the “Add” method in the class.
In the next step, we create an instance of the delegate and pass the “Add” method as the parameter. This encapsulates the “Add” method into the delegate.
Lastly, we invoke the delegate like a regular method.
Delegates for Callbacks
As we mentioned, delegates are especially useful when implementing the callbacks. A callback is basically a method that is called when a task is completed. This provides a way of passing the data back or continue the program execution once the task is complete.
Take the following example:
public class Worker
{
public void DoWork(CallbackDelegate callback)
{
Console.WriteLine("Working...");
Thread.Sleep(1000);
callback("task completed!");
}
}
public class Program
{
public static void Main()
{
Worker worker = new Worker();
CallbackDelegate callback = new CallbackDelegate(OnWorkCompleted);
worker.DoWork(callback);
}
public static void OnWorkCompleted(string message)
{
Console.WriteLine(message);
}
}
- We start by defining a callback delegate which encapsulates the method that takes a string parameter and returns void.
- In the second section, we define a class with a “DoWork” method which accepts a delegate as the parameter. This performs a task and calls the callback delegate.
Output:
task completed!
Conclusion
In this tutorial, we learned the basics of creating and using delegates in C#. We also discussed how to use the delegates for callbacks.