This article will demonstrate you about all interview questions related to delegate with practical implementation.
What is Delegate?
A delegate is reference type that basically encapsulates the reference of methods. It is a similar to class that store the reference of methods which have same signature as delegate has.
It is very similar to a function pointer in C++, but delegate is type safe, object oriented and secure as compare to C++ function pointer.
Why do we use Delegate?
There are following reason because of we use delegate.
- It is used for type safety.
- For executing multiple methods through one execution.
- It allows us to pass methods as parameter.
- For asynchronous programming.
- For Call back method implementation.
- It is also used when working with event based programming.
- When creating anonymous method.
- When working with lambda expression.
How many types of Delegate in C#?
There are three types of delegates available in C#.
- Simple/Single Delegate
- Multicast Delegate
- Generic Delegate
What are the ways to create and use delegate?
There are only five steps to create and use a delegate and these are as following.
- Declare a delegate type.
- Create or find a method which has same type of signature.
- Create object/instance of delegate
- Pass the reference of method with delegate instance.
- At last Invoke the delegate object.
For more about refer this article "Delegate in C#"
What is Single Delegate?
When Delegate takes reference with single method only then it is called Single Delegate. It is used for invocation of only one reference method.
Following example has a delegate name as "TestDelegate" with one parameter as string.
using System;
namespace EventAndDelegateExamples
{
delegate void TestDelegate(string name);
class FunctionPointerExample
{
public void GetName(string name)
{
Console.WriteLine("Full Name is : " + name);
}
}
}
Below code snippet that first we are creating a instance of TestDelegate and passing the reference of method "objFunctionPointerExample.GetName" method with objDelegate1.
FunctionPointerExample objFunctionPointerExample = new FunctionPointerExample();
//Call GetName function using TestDelegate
TestDelegate objDelegate1 = new TestDelegate(objFunctionPointerExample.GetName);
objDelegate1.Invoke("Mukesh Kumar");
To invoke the delegate, just need to use Invoke method to pass required parameter.
What is Multicast Delegate?
When Delegate takes reference with multiple methods then it is called multicast delegate. It is used for invocation of multiple reference methods. We can add or remove references of multiple methods with same instance of delegate using (+) or (-) sign respectively. It need to consider here that all methods will be invoked in one process and that will be in sequence.
Following example has a delegate name as "TestMultiCastDelegate" with one parameter as int.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EventAndDelegateExamples
{
delegate void TestMultiCastDelegate(int a);
class MultiCastDelegateExample
{
internal void GetSalary(int AnnualSalary)
{
Console.WriteLine("Monthly Salary is "+ AnnualSalary / 12);
}
internal void GetSalaryAfterDeduction(int AnnualSalary)
{
if (AnnualSalary > 12000)
{
Console.WriteLine("Monthly Salry after deduction is "+ ((AnnualSalary / 12) - 500));
}
else
{
Console.WriteLine("Monthly Salry after deduction is " +AnnualSalary / 12);
}
}
}
}
Below code snippet shows that first we are creating a instance of TestMultiCastDelegate and passing the reference of methods [GetSalary] and [GetSalaryAfterDeduction] with "objDelegate2".
MultiCastDelegateExample objMultiCastDelegateExample = new MultiCastDelegateExample();
//Creating the instance of the delegate
TestMultiCastDelegate objDelegate2 = null;
//Referencing the multiple methods using + sign
objDelegate2 += objMultiCastDelegateExample.GetSalary;
objDelegate2 += objMultiCastDelegateExample.GetSalaryAfterDeduction;
objDelegate2.Invoke(60000);
How to achieve callback in Delegate?
Callback is term where a process is going on and in between it targets some achievement then it return to main method. For callback, we just need to encapsulate the method with delegate.
objCallBackMethodExample.CheckEvenEvent += new OnEvenNumberHandler(objCallBackMethodExample.CallBackMethod);
Let see an example, CallBackMethodExample is a class which have a method CallBackMethod. It will be executed when some criteria will be fulfill.
public delegate void OnEvenNumberHandler(object sender, EventArgs e);
public class CallBackMethodExample
{
public void CallBackMethod(object sender, EventArgs e)
{
Console.WriteLine("Even Number has found !");
}
}
When we are going to call this method using Delegate for callback, only need to pass this method name as a reference.
CallBackMethodExample objCallBackMethodExample = new CallBackMethodExample();
objCallBackMethodExample.CheckEvenEvent += new OnEvenNumberHandler(objCallBackMethodExample.CallBackMethod);
Random random = new Random();
for (int i = 0; i < 6; i++)
{
var randomNumber = random.Next(1, 10);
Console.WriteLine(randomNumber);
if (randomNumber % 2 == 0)
{
objCallBackMethodExample.OnCheckEvenNumber();
}
}
How to achieve Async callback in Delegate?
Async callback means, process will be going on in background and return back when it will be completed. In C#, Async callback can be achieved using AsyncCallback predefined delegate as following.
public delegate void AsyncCallback(IAsyncResult ar);
Kindly follow the following example to understand the Async callback. There is a class name as CallBackMethodExample which have two method, one is TestMethod and other one is AsyncCallBackFunction. But as we can see AsyncCallBackFunction is taking IAsyncResult as a parameter.
public delegate void OnEvenNumberHandler(object sender, EventArgs e);
public class CallBackMethodExample
{
public void TestMethod(object sender, EventArgs e)
{
Console.WriteLine("This is simple test method");
}
public void AsynCallBackFunction(IAsyncResult asyncResult)
{
OnEvenNumberHandler del = (OnEvenNumberHandler)asyncResult.AsyncState;
del.EndInvoke(asyncResult);
Console.WriteLine("Wait For 5 Seconds");
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Async Call Back Function Completed");
}
}
When we are going to invoke the delegate, only just need to pass AsycnCallBackFunction with delegate instance.
CallBackMethodExample objCallBackMethodExample = new CallBackMethodExample();
OnEvenNumberHandler objDelegate3 = new OnEvenNumberHandler(objCallBackMethodExample.TestMethod);
objDelegate3.BeginInvoke(null, EventArgs.Empty, new AsyncCallback(objCallBackMethodExample.AsynCallBackFunction), objDelegate3);
Console.WriteLine("End of Main Function");
Console.WriteLine("Waiting for Async Call Back Function");
How many other ways to create delegate in C#?
There are different ways to create delegate in C#.
- Action
- Func
- Predicate
rahul kumar Posted : 6 Years Ago
Its a good article. Could please provide complete code of this example?