Delegates, Func, and Action


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. delegate string DelegateTest(string testString); // setup delegate with its signature.
  2.  
  3. DelegateTest ma; // create instance of delegate
  4.  
  5. //--------------------------------------------------------Methods to run with same signatures
  6. static string DelTest1(string input)
  7. {
  8. return input + "---";
  9. }
  10. //----------------------------------------------
  11. static string DelTest2(string input)
  12. {
  13. string modifiedString = input.Substring(7, input.Length - 7);
  14.  
  15. modifiedString += "--- This would be awesome if this works";
  16.  
  17. return modifiedString;
  18. }
  19. //-------------------------------------------------------------------
  20.  
  21. public void setUpMethod(string test) // Setup to start things----Optional
  22. {
  23. ma = DelTest1; // Assign delegate to a method.
  24.  
  25. Console.WriteLine(ma(test)); // Run delegate method
  26. Console.ReadLine();
  27.  
  28. ma = DelTest2; // Reassign delegate to another method.
  29.  
  30. Console.WriteLine(ma(test)); // Run delegate using another method.
  31. Console.ReadLine();
  32. }
  33.  
  34. setUpMethod("testing123");
  35.  
  36.  
  37. OUTPUT:
  38. testing123---
  39. 123--- This would be awesome if this works
  40. ============================================================================================
  41. The alternate to this is to use a Func<T>.
  42.  
  43. Func<string, string> ma = DelTest1; // put this inside of setUpMethod.
  44. 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.
  45.  
  46. ============================================================================================
  47.  
  48. Action<T> is a Func<T> without the return.
  49.  
  50. Action<string> write = x => Console.WriteLine(x);
  51. write("This is a test and only a test);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.