What is Delegate in C#?
C# delegates are pointers to functions or methods. A delegate is a reference type variable that holds the reference to a method.
The reference can be changed at the runtime. Delegates are especially used for implementing events and the call-back methods.
All the delegates are implicitly derived from the System.Delegate class.
E.g.:
delegateintSampleDelegate(int i, int j);
public class ABC
{
static void Main(string[] args)
{
SampleDelegate del = newSampleDelegate(SampleMethod1);
del.Invoke(10, 20);
}
int SampleMethod1(int a, int b)
{
returna + b;
}
}
Delegate is type safe function pointer to a method. Delegate can be passed as a parameter to a method.
Tips : To learn more about C # Programming : Learn C# App.
When to Use Delegate:
1. If you don’t want to pass your interface or abstract class dependence to internal class or layers.
2. If the code doesn't need access to any other attributes or method of the class from which logic needs to be processed.
3. Event driven implementation needs to be done.
Delegates Types:
1. Func:
Delegate for a function which may or may not take parameters and return a value.Always Last Parameter is the OUT parameter in Func.
E.g.:
public class ABC
{
static void Main(string[] args)
{
Func < int, string, decimal, string > DisplayEmp = newFunc < int, string, decimal, string > (CreateEmployee);
Console.WriteLine(DisplayEmp(1, "Rakesh", 2000));
}
privatestaticstringCreateEmployee(int no, string Name, decimal Salary) {
returnstring.Format("EmployeeNo:{0} \n Name:{1} \n Salary:{2}", no, Name, Salary);
}
}
2. Action:
Delegate for a function which may or may not take parameters and does not return a value.
E.g.:
public class ABC
{
static void Main(string[] args)
{
Action < string, string > FullName = newAction < string, string > (DisplayName);
FullName("Rakesh", "Dabde");
}
privatestaticvoidDisplayName(stringFirstName, stringLastName) {
Console.WriteLine("FullName : {0} {1}", FirstName, LastName);
}
}
3. Predicate:
It is specialized version of Func which takes argument. Delegate returns Boolean value.
public class ABC
{
static void Main(string[] args)
{
Predicate < int > GreaterValue = newPredicate < int > (IsGreater);
Console.WriteLine(GreaterValue(900));
}
privatestaticboolIsGreater(intobj)
{
return (obj > 1000) ? true : false;
}
}
Tips : To learn more about C # Programming : Learn C# App.
No comments :