Saturday, February 02, 2013

Delegates: Passing methods as Arguments

Methods can be passed to another methods through delegates.
Find below the sample for Passing methods as Arguments
namespace PassingMethodAsArgument {
     public class Program {
         static void Main(string[] args) {
             // Pass method as argument to another method
            CalcNPrint(Add, 10, 5);
            CalcNPrint(Mul, 10, 5);
            Console.ReadKey();
         }
         // Receive method as parameter using delegate
        public static void CalcNPrint(Calc calc, int m, int n) {
             var strMethodName = calc.Method.Name;
             var intResult = calc.Invoke(m,n);
             Console.WriteLine("{0}({1},{2}) = {3}", strMethodName, m, n, intResult);
         }
         // Functions that matches Calc delegate signature
        public static int Add(int x, int y) {
             return x + y;
         }
         public static int Mul(int x, int y) {
             return x * y;
         }
     }     // Define delegate
    public delegate int Calc(int a, int b);
     }

No comments:

Post a Comment