Func And Action Delegate

Action and Func are existing delegates that are generic. I’ll go through the implementation of all the three -Delegate, Action, and Func. After implementing the delegate, you will understand better about Action and Func delegates.
 

Delegate

 
It holds the reference of the method.
  1. public delegate void Write(String value);  
  2. public static void Main() {  
  3.     Write write = WriteTheText;  
  4.     write("Hello");  
  5.     var text = "I enjoyed the movie";  
  6.     write(text);  
  7. }  
  8. public static void WriteTheText(string value) {  
  9.     Console.WriteLine(value);  
  10. }  
  11. public delegate void Write(String value); - First we are declaring the delegate  
  12. Write write = WriteTheText; - Write is the delegate which has the reference of the“ WriteTheText” method.  
  13. write("Hello"); - We are invoking the delegate.It will call the“ WriteTheText” method and send the parameter“ Hello”.  

Action

 
Now, let’s try the same with Action. Action delegate is the existing delegate. In this, we can pass zero to 16 parameters. 
  1. public static void Main() {  
  2.     Action < string > write = WriteTheText;  
  3.     write("Hello");  
  4.     var text = "I enjoyed the movie";  
  5.     write(text);  
  6. }  
  7. public static void WriteTheText(string value) {  
  8.     Console.WriteLine(value);  
  9. }  
We are holding the reference of the “WriteTheText” method in the Action delegate. There is no need to declare the Action delegate.
  1. Action<string> write = WriteTheText;  

Func

 
This also works like Action delegate but it returns value. 
  1. public static void Main() {  
  2.     Func < stringbool > write = WriteTheText;  
  3.     var IsPrinted = write("Hello");  
  4.     var text = "I enjoyed the movie";  
  5.     var IsWritten = write(text);  
  6. }  
  7. public static bool WriteTheText(string value) {  
  8.     Console.WriteLine(value);  
  9.     return true;  
  10. }  
The second Parameter in the Func<string,bool> is the return type. Bool is the return type of the func delegate.
 
Func And Action Delegate
 
After the execution, “true”(default value in this example) is returned. IsPrinted variable value is “true”.
 
Output in all the scenarios.
 
Func And Action Delegate