December 20, 2009

The Action delegates

You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (In C#, the method must return void.)
The framework defines a number of parameterized delegate types for delegates that return void:

public delegate void Action();
public delegate void Action<T0>(T0 a0);
public delegate void Action<T0, T1>(T0 a0, T1 a1);
public delegate void Action<T0, T1, T2>(T0 a0, T1 a1, T2 a2);
public delegate void Action<T0, T1, T2, T3>(T0 a0, T1 a1, T2 a2, T3 a3);
Let see an example written in different forms using Action, delegate, action with anonymous method & action with lambda expression  -

The Action which takes one input param
public delegate void Action<T0>(T0 a0);

class ActionTest
{
static void Main(string[] args)
{
Action<string> PrintResultMethod = PrintResult;
PrintResultMethod("Hello, World!");
}

private static void PrintResult(string inStr)
{
Console.WriteLine(inStr);
}
}
Delegates instead of Action
Following example shows use of delegate instead of action

delegate void PrintResultMethod(string inStr);
public class DelegateTest
{
    public static void Main()
    {
        // Instantiate delegate  
        PrintResultMethod printResultMethod = PrintResult;

        // Use delegate instance to call PrintResult method
        printResultMethod("Hello World");
    }

    private static void PrintResult(string inStr)
    {
        Console.WriteLine(inStr);             
    }
}


Action with anonymous method
class ActionwithAnonymous
{
static void Main(string[] args)
{
Action<string> PrintResultMethod = delegate(string s) { PrintResult(s); };
PrintResultMethod("Hello, World!");
}

private static void PrintResult(string inStr)
{
Console.WriteLine(inStr);
}
}

Action with lambda expressions
public class ActionWithLambda
{
public static void Main()
{
Action<string> PrintResultMethod = s => PrintResult(s);
PrintResultMethod("Hello, World!");
}
private static void PrintResult(string inStr)
{
Console.WriteLine(inStr);
}
}