Interviews4 answers
What is Delegates and Use of Delegates in C#?
4 Answers
Delegate are used to wrap the method
So any one can not recognize
This method is of which class
Mukesh KumarPosted Aug 29, 2017, 4:36 PM EDT
Delegate is a function pointer. It holds the reference of function.
Example - Suppose you have a class Vodafone. And it has 3 functions like 20rs,30rs and 40rs tariff voucher. So if you provide the object of this vodafone class then user can access all the tariff voucher. But if you will provide only a 20rs tariff voucher function reference (delegate) to the user then he can access that function. User can'nt access other tariff voucher. For more info please do practice.
Sudheshwer RaiPosted Jun 1, 2017, 3:49 AM EDT
Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.
Emamul HasanPosted Feb 27, 2017, 2:26 AM EST
Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net.
Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.
Example
public delegate int DelegateExample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegateExample delgat1 = sc.Add;
int i = delgat1(5, 5);
Console.WriteLine(i);
DelegateExample delgat2 = sc.Sub;
int j = delgat2(5, 2);
Console.WriteLine(j);
}
}
Output
Add Result : 10
Sub Result : 3
Use of Delegates
if we have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.
Delegate's Types:
1. Single and Multi Caste Delegate
Gnanavel SekarPosted Jan 16, 2017, 11:42 PM EST



