|
| 1 | + |
| 2 | +using System; |
| 3 | + |
| 4 | +class SendingMethodToMethodDemo |
| 5 | +{ |
| 6 | + static void Main() |
| 7 | + { |
| 8 | + // Sending Named methods to ReceiverMethod() |
| 9 | + ReceiverMethod(SquareMethod, "Named"); |
| 10 | + ReceiverMethod(IsEvenMethod, "Named"); |
| 11 | + ReceiverMethod(PrintMessageMethod, "Named"); |
| 12 | + |
| 13 | + // Sending Anonymous methods to ReceiverMethod |
| 14 | + ReceiverMethod(delegate (int x) { return x * x; }, "Anonymous"); |
| 15 | + ReceiverMethod(delegate (int x) { return x % 2 == 0; }, "Anonymous"); |
| 16 | + ReceiverMethod(delegate (string s) { Console.Write(s); }, "Anonymous"); |
| 17 | + |
| 18 | + // Sending methods using Lambda expression |
| 19 | + ReceiverMethod(x => x * x, "Lambda"); |
| 20 | + ReceiverMethod(x => x % 2 == 0, "Lambda"); |
| 21 | + ReceiverMethod(s => Console.Write(s), "Lambda"); |
| 22 | + } |
| 23 | + |
| 24 | + // Named method for demonstration of sending method via Func |
| 25 | + static int SquareMethod(int x) |
| 26 | + { |
| 27 | + return x * x; |
| 28 | + } |
| 29 | + |
| 30 | + // Named method for demostration of sending method via Predicate |
| 31 | + static bool IsEvenMethod(int x) |
| 32 | + { |
| 33 | + return x % 2 == 0; |
| 34 | + } |
| 35 | + |
| 36 | + // Named method for demonstration of sending method via Action |
| 37 | + static void PrintMessageMethod(string msg) |
| 38 | + { |
| 39 | + Console.Write(msg); |
| 40 | + } |
| 41 | + |
| 42 | + // Overloaded Method to execute a Func<int, int> type method |
| 43 | + static void ReceiverMethod(Func<int, int> parcelMethod, string parcelType) |
| 44 | + { |
| 45 | + Console.Write("Received method using " + parcelType); |
| 46 | + Console.Write(parcelType[0]=='L'? " expression" : " method"); |
| 47 | + Console.Write("-Func: Square of 5 = "); |
| 48 | + int result = parcelMethod(5); |
| 49 | + Console.WriteLine(result); |
| 50 | + } |
| 51 | + |
| 52 | + // Overloaded Method to execute a Predicate<int> type method |
| 53 | + static void ReceiverMethod(Predicate<int> parcelMethod, string parcelType) |
| 54 | + { |
| 55 | + Console.Write("Received method using " + parcelType); |
| 56 | + Console.Write(parcelType[0]=='L'? " expression" : " method"); |
| 57 | + Console.Write("-Predicate: Is 4 Even = "); |
| 58 | + bool result = parcelMethod(4); |
| 59 | + Console.WriteLine(result); |
| 60 | + } |
| 61 | + |
| 62 | + // Overloaded Method to execute an Action<string> type method |
| 63 | + static void ReceiverMethod(Action<string> parcelMethod, string parcelType) |
| 64 | + { |
| 65 | + parcelMethod("Received method using " + parcelType); |
| 66 | + Console.Write(parcelType[0]=='L'? " expression" : " method"); |
| 67 | + Console.WriteLine("-Action"); |
| 68 | + } |
| 69 | +} |
0 commit comments