Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Action<string>?

Tags:

What is Action<string>, how can it be used?

like image 436
learning Avatar asked May 14 '10 12:05

learning


People also ask

What is the action in C#?

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.

What is the difference between action and func?

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).

What is the delegate in C#?

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.


2 Answers

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

like image 159
Julien Hoarau Avatar answered Sep 21 '22 19:09

Julien Hoarau


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

like image 22
Ruben Avatar answered Sep 18 '22 19:09

Ruben