Func explained
Func is a generic delegate supplied for your use by the language. You can use Func instead of creating your own delegate.
Func always returns a value.
Func is overloaded and can take up to 16 input arguments
e.g.
Func takes 2 integers and returns a bool
Func takes 2 strings, 1 integer and returns a double
Example
1. I create a delegate which takes 2 ints and returns an int: delegate int delSum(int a, int b);
2. I create a method with a matching signature:
static int Add(int x, int y)
{
return x + y;
}
3. I add the “Add” method to the delegate’s invocation list and then I invoke it
delSum ds = new delSum(Add);
Console.WriteLine(ds(2,3));
4. Instead of going to the trouble of creating my own delegate, I use the generic Func delegate instead
Func f = Add;
Console.WriteLine(f(2, 3));
————————————————————
Action explained
Action is a generic delegate supplied for your use by the language. You can use Action instead of creating your own delegate.
Action never returns a value.
Action is overloaded and can take up to 16 input arguments
Example
1. I create a delegate which takes 2 strings and returns nothing ( void ): delegate void delOutput(string fName, string lname);
2. I create a method with a matching signature:
static void DisplayFullName(string fName, string lname)
{
Console.WriteLine(fName + ” ” + lname);
}
3. I add the “DisplayFullName” method to the delegate’s invocation list and then I invoke it
delOutput op = new delOutput(DisplayFullName);
op(“Stanley”, “Fletcher”);
4. Instead of going to the trouble of creating my own delegate, I use the generic Action delegate instead
Action a = DisplayFullName;
a(“Stanley”, “Fletcher”);

Leave a comment