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;
- }
- }
- 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);
- }
- }
Pradeep SahooPosted Apr 24, 2016, 12:23 AM
Nice Information on Generic delegates .Thanks for sharing