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.
- public delegate void Write(String value);
- public static void Main() {
- Write write = WriteTheText;
- write("Hello");
- var text = "I enjoyed the movie";
- write(text);
- }
- public static void WriteTheText(string value) {
- Console.WriteLine(value);
- }
- public delegate void Write(String value); - First we are declaring the delegate
- Write write = WriteTheText; - Write is the delegate which has the reference of the“ WriteTheText” method.
- 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.
- public static void Main() {
- Action < string > write = WriteTheText;
- write("Hello");
- var text = "I enjoyed the movie";
- write(text);
- }
- public static void WriteTheText(string value) {
- Console.WriteLine(value);
- }
We are holding the reference of the “WriteTheText” method in the Action delegate. There is no need to declare the Action delegate.
- Action<string> write = WriteTheText;
Func
This also works like Action delegate but it returns value.
- public static void Main() {
- Func < string, bool > write = WriteTheText;
- var IsPrinted = write("Hello");
- var text = "I enjoyed the movie";
- var IsWritten = write(text);
- }
- public static bool WriteTheText(string value) {
- Console.WriteLine(value);
- return true;
- }
The second Parameter in the Func<string,bool> is the return type. Bool is the return type of the func delegate.
After the execution, “true”(default value in this example) is returned. IsPrinted variable value is “true”.
Output in all the scenarios.