Delegates & Callbacks
Introduction
A "callback" is a term that refers to a coding design pattern. In this design pattern executable code is passed as an argument to other code and it is expected to call back at some time. This callback can be synchronous or asynchronous. So, in this way large piece of the internal behavior of a method from the outside of a method can be controlled. It is basically a function pointer that is being passed into another function.
Delegate is a famous way to implement Callback in C#. But, it can also be implemented by Interface. I will explain Callback by Delegate and Interface one by one.
Callback by Delegate
Delegate provides a way to pass a method as argument to other method. To create a Callback in C#, function address will be passed inside a variable. So, this can be achieved by using Delegate.
The following is an example of Callback by Delegate
public delegate void TaskCompletedCallBack(string taskResult); public class CallBack { public void StartNewTask(TaskCompletedCallBack taskCompletedCallBack) { Console.WriteLine("I have started new Task."); if (taskCompletedCallBack != null) taskCompletedCallBack("I have completed Task."); } }
C#Copy
public class CallBackTest { public void Test() { TaskCompletedCallBack callback = TestCallBack; CallBack testCallBack = new CallBack(); testCallBack.StartNewTask(callback); } public void TestCallBack(string result) { Console.WriteLine(result); } }
C#Copy
static void Main(string[] args) { CallBackTest callBackTest = new CallBackTest(); callBackTest.Test(); Console.ReadLine(); }