Action and Func are the generic type delegates. Both are defined under System namespace. So in your program you do not need to define it.
Action
Encapsulate any types of method which match the following signature.
1. Has a void return type.
2. Has up to 16 parameters. All parameters in Action are defined as generic.
Func
1. Has up to 17 parameters. All parameters in Action are defined as generic.
2. It has a return type.
3. Last parameter is always an output parameter. It is also implemented as generic so it can return any value.
Below are the compete codes
Output:
-Start program-
Call by Action
Call by Func
I am returned from Function2
Happy coding...:)
Action
Encapsulate any types of method which match the following signature.
1. Has a void return type.
2. Has up to 16 parameters. All parameters in Action are defined as generic.
Action<string> act = new Action<string>(a.Function1);
Func
1. Has up to 17 parameters. All parameters in Action are defined as generic.
2. It has a return type.
3. Last parameter is always an output parameter. It is also implemented as generic so it can return any value.
Func<string string> fun = new Func<string string>(a.Function2);
Below are the compete codes
using System; namespace TestDelegate { class Program { static void Main(string[] args) { Console.WriteLine("-Start program-"); ABC a = new ABC(); Action<string> act = new Action<string>(a.Function1); act.Invoke("Call by Action"); Func<string string> fun = new Func<string string>(a.Function2); var result = fun.Invoke("Call by Func"); Console.WriteLine(result.ToString()); Console.ReadKey(); } } class ABC { public void Function1(string s) { Console.WriteLine(s); } public string Function2(string s) { Console.WriteLine(s); return "I am returned from Function2"; } } }
Output:
-Start program-
Call by Action
Call by Func
I am returned from Function2
Happy coding...:)