I need a generic C# module that will execute different functions for some classes, or execute none. This can be done with delegates.
The basic info is described in MSDN articles:
Using Delegates (C# Programming Guide)
Func<T, TResult> Delegate
Here is my simple console application that would call different functions that are passed as parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // instantiate delegates DelegateDeclaration h1 = DelegateImplementation1; DelegateDeclaration h2 = DelegateImplementation2; // call delegate ExecuteHandler(null); ExecuteHandler(h1); ExecuteHandler(h2); } // declaration public delegate int DelegateDeclaration(int n); // implementation public static int DelegateImplementation1(int n) { Console.WriteLine("Input parameter: " + n); return n * 2; } public static int DelegateImplementation2(int n) { Console.WriteLine("Input parameter: " + n); return n * 3; } // function with a delegate function parameter public static void ExecuteHandler(DelegateDeclaration handler) { if (handler == null) { Console.WriteLine("Delegate handler is null"); } else { int r = handler(5); Console.WriteLine("Result: " + r); } } } } |
Andrey, I love your blog. Your examples are on spot. Thanks for sharing this 🙂
Thanks