What is Action<string>
, how can it be used?
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. For example, the following delegate prints an int value.
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything. Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Action
is a standard delegate that has one to 4 parameters (16 in .NET 4) and doesn't return value. It's used to represent an action.
Action<String> print = (x) => Console.WriteLine(x);
List<String> names = new List<String> { "pierre", "paul", "jacques" };
names.ForEach(print);
There are other predefined delegates :
Predicate
, delegate that has one parameter and returns a boolean.
Predicate<int> predicate = ((number) => number > 2);
var list = new List<int> { 1, 1, 2, 3 };
var newList = list.FindAll(predicate);
Func
is the more generic one, it has 1 to 4 parameters (16 in .NET 4) and returns something
This is a delegate to a function with the signature
void Bla(string parameter)
. You can use this to pass functions to other functions.
For instance you can do this
Action<string> action = (x => Console.WriteLine(x));
new List<string>{"1","2","3"}.ForEach(action);
to print all characters to the console
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With