Delegates:
Delegate is type safe function pointer to a method. Delegate can be passed as a parameter to a method.
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;
- }
- }
When to Use Delegate:
- If you don’t want to pass your interface or abstract class dependence to internal class or layers.
- If the code doesn't need access to any other attributes or method of the class from which logic needs to be processed.
- 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.:
- 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);
- }
- }
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);
- }
- }
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;
- }
- }