/ Published in: C#
A delegate is a reference to any method that has the same signature. The benefit of this is that the delegate can switch to another method with the same signature, without changing itself.
Func is a way to simplify the delegate creation and use.
Action is a Func without the return type.
Func is a way to simplify the delegate creation and use.
Action is a Func without the return type.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
delegate string DelegateTest(string testString); // setup delegate with its signature. DelegateTest ma; // create instance of delegate //--------------------------------------------------------Methods to run with same signatures static string DelTest1(string input) { return input + "---"; } //---------------------------------------------- static string DelTest2(string input) { string modifiedString = input.Substring(7, input.Length - 7); modifiedString += "--- This would be awesome if this works"; return modifiedString; } //------------------------------------------------------------------- public void setUpMethod(string test) // Setup to start things----Optional { ma = DelTest1; // Assign delegate to a method. Console.WriteLine(ma(test)); // Run delegate method Console.ReadLine(); ma = DelTest2; // Reassign delegate to another method. Console.WriteLine(ma(test)); // Run delegate using another method. Console.ReadLine(); } setUpMethod("testing123"); OUTPUT: testing123--- 123--- This would be awesome if this works ============================================================================================ Func<string, string> ma = DelTest1; // put this inside of setUpMethod. With this you don't have to instantiate a delegate object or setup the delegate. The first string in this example is the input(you can have up to 15 separated by comma). The second string is the output, what is returned. ============================================================================================ Action<T> is a Func<T> without the return. Action<string> write = x => Console.WriteLine(x); write("This is a test and only a test);