Delegates and Types of Delegates

Delegates:

Delegate is type safe function pointer to a method. Delegate can be passed as a parameter to a method.

E.g.:

  1. delegateintSampleDelegate(int i, int j);  
  2. public class ABC   
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         SampleDelegate del = newSampleDelegate(SampleMethod1);  
  7.         del.Invoke(10, 20);  
  8.     }  
  9.     int SampleMethod1(int a, int b)  
  10.     {  
  11.         returna + b;  
  12.     }  
  13. }  
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:

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.:

  1. public class ABC  
  2. {  
  3.     static void Main(string[] args)   
  4.     {  
  5.         Func < intstringdecimalstring > DisplayEmp = newFunc < intstringdecimalstring > (CreateEmployee);  
  6.         Console.WriteLine(DisplayEmp(1, "Rakesh", 2000));  
  7.     }  
  8.     privatestaticstringCreateEmployee(int no, string Name, decimal Salary) {  
  9.         returnstring.Format("EmployeeNo:{0} \n Name:{1} \n Salary:{2}", no, Name, Salary);  
  10.     }  
  11. }  
Action:

Delegate for a function which may or may not take parameters and does not return a value.

E.g.:
  1. public class ABC   
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Action < stringstring > FullName = newAction < stringstring > (DisplayName);  
  6.         FullName("Rakesh""Dabde");  
  7.     }  
  8.     privatestaticvoidDisplayName(stringFirstName, stringLastName) {  
  9.         Console.WriteLine("FullName : {0} {1}", FirstName, LastName);  
  10.     }  
  11. }  
Predicate:

It is specialized version of Func which takes argument. Delegate returns Boolean value.

 

  1. public class ABC  
  2. {  
  3.     static void Main(string[] args)   
  4.     {  
  5.         Predicate < int > GreaterValue = newPredicate < int > (IsGreater);  
  6.         Console.WriteLine(GreaterValue(900));  
  7.     }  
  8.     privatestaticboolIsGreater(intobj)  
  9.     {  
  10.         return (obj > 1000) ? true : false;  
  11.     }  
  12. }