views:

174

answers:

7

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

+5  A: 

It is a delegate with one parameter, this being a string.

Usefull because it means you do not have to create delegates anymore for actions as long as you can use a standard action for them (i.e. the number of parameters is fixed, no default values and you can just use an existing action).

TomTom
A: 

Hi,

here is a small and easy introduction of Action:

http://www.c-sharpcorner.com/UploadFile/rmcochran/anonymousMethods04022006141542PM/anonymousMethods.aspx

MUG4N
+1  A: 

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

Ruben
+1 You were the only person to provide a meaningful example.
Brian Gideon
A: 

It is basically just a delegate that does not return a value.

Have a look here: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

Action<string> would just be a delegate of a mehtod that excepted a single string parameter and did not return anything.

MarkB29
+3  A: 

From the documentation:

Encapsulates a method that has a single parameter and does not return a value.

Usage example (taken from the documentation and simplified):

Action<string> myMessageShowAction;

if (...)
    myMessageShowAction = s => Console.WriteLine(s);
else
    myMessageShowAction = ... /* some other way to show a message */

myMessageShowAction("Hello, World!"); // this will use whatever action has been put into myMessageShowAction

Delegates allow you to store anonymous methods (or pointers to existing methods) in a variable. Action<string> is a delegate for a method that takes one string as a parameter and does not return a value.

Heinzi
A: 
public void ValidateInput(string input)
{
   //some code
}

public void test()
{
   Action<string> action = ValidateInput;
}
Sachin
+8  A: 

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

madgnome
I believe "1 to 16 parameters" is only available from .NET 4 though?
Patrick
+1 for mentioning Predicate and giving examples
milan1612
Thanks, You're right Patrick, I've updated it.
madgnome