Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System Namespace
 Action(T) Delegate
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Action<(Of <(T>)>) Delegate

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
Public Delegate Sub Action(Of T) ( _
    obj As T _
)
Visual Basic (Usage)
Dim instance As New Action(Of T)(AddressOf HandlerMethod)
C#
public delegate void Action<T>(
    T obj
)
Visual C++
generic<typename T>
public delegate void Action(
    T obj
)
JScript
JScript does not support generic types or methods.

Type Parameters

T

The type of the parameter of the method that this delegate encapsulates.

Parameters

obj
Type: T
The parameter of the method that this delegate encapsulates.

You can use this delegate to pass a method as a parameter without explicitly declaring a custom delegate. The 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 must not return a value. (In C#, the method must return void. In Visual Basic, it must be defined by the SubEnd Sub construct.) Typically, such a method is used to perform an operation.

018hxwa8.alert_note(en-us,VS.90).gifNote:

To reference a method that has one parameter and returns a value, use the generic Func<(Of <(T, TResult>)>) delegate instead.

When you use the Action<(Of <(T>)>) delegate, you do not have to explicitly define a delegate that encapsulates a method with a single parameter. For example, the following code explicitly declares a delegate named DisplayMessage and assigns a reference to either the WriteLine method or the ShowWindowsMessage method to its delegate instance.

Visual Basic
Delegate Sub DisplayMessage(message As String) 

Module TestCustomDelegate
   Public Sub Main
      Dim messageTarget As DisplayMessage 

      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = AddressOf ShowWindowsMessage
      Else
         messageTarget = AddressOf Console.WriteLine
      End If
      messageTarget("Hello, World!")
   End Sub

   Private Sub ShowWindowsMessage(message As String)
      MsgBox(message)
   End Sub   
End Module

C#
using System;
using System.Windows.Forms;

delegate void DisplayMessage(string message);

public class TestCustomDelegate
{
   public static void Main()
   {
      DisplayMessage messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");   
   }      

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}

The following example simplifies this code by instantiating the Action<(Of <(T>)>) delegate rather than explicitly defining a new delegate and assigning a named method to it.

Visual Basic
Module TestAction1
   Public Sub Main
      Dim messageTarget As Action(Of String) 

      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = AddressOf ShowWindowsMessage
      Else
         messageTarget = AddressOf Console.WriteLine
      End If
      messageTarget("Hello, World!")
   End Sub

   Private Sub ShowWindowsMessage(message As String)
      MsgBox(message)
   End Sub   
End Module

C#
using System;
using System.Windows.Forms;

public class TestAction1
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");   
   }      

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}

You can also use the Action<(Of <(T>)>) delegate with anonymous methods in C#, as the following example illustrates. (For an introduction to anonymous methods, see Anonymous Methods (C# Programming Guide).)

C#
using System;
using System.Windows.Forms;

public class TestAnonMethod
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = delegate(string s) { ShowWindowsMessage(s); };
      else
         messageTarget = delegate(string s) { Console.WriteLine(s); };

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}

You can also assign a lambda expression to an Action<(Of <(T>)>) delegate instance, as the following example illustrates. (For an introduction to lambda expressions, see Lambda Expressions (C# Programming Guide).)

C#
using System;
using System.Windows.Forms;

public class TestLambdaExpression
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = s => ShowWindowsMessage(s); 
      else
         messageTarget = s => Console.WriteLine(s);

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}

018hxwa8.alert_note(en-us,VS.90).gifNote:

Visual Basic requires that a lambda expression return a value. As a result, the Action<(Of <(T>)>) delegate cannot be used with a lambda expression in Visual Basic.

The ForEach and ForEach<(Of <(T>)>) methods each take an Action<(Of <(T>)>) delegate as a parameter. The method encapsulated by the delegate allows you to perform an action on each element in the array or list. The example uses the ForEach method to provide an illustration.

The following example demonstrates the use of the Action<(Of <(T>)>) delegate to print the contents of a List<(Of <(T>)>) object. In this example, the Print method is used to display the contents of the list to the console. In addition, the C# example also demonstrates the use of anonymous methods to display the contents to the console.

Visual Basic
Imports System
Imports System.Collections.Generic

Class Program
    Shared Sub Main()
        Dim names As New List(Of String)
        names.Add("Bruce")
        names.Add("Alfred")
        names.Add("Tim")
        names.Add("Richard")

        ' Display the contents of the list using the Print method.
        names.ForEach(AddressOf Print)
    End Sub

    Shared Sub Print(ByVal s As String)
        Console.WriteLine(s)
    End Sub
End Class

' This code will produce output similar to the following:
' Bruce
' Alfred
' Tim
' Richard

C#
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<String> names = new List<String>();
        names.Add("Bruce");
        names.Add("Alfred");
        names.Add("Tim");
        names.Add("Richard");

        // Display the contents of the list using the Print method.
        names.ForEach(Print);

        // The following demonstrates the anonymous method feature of C#
        // to display the contents of the list to the console.
        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
/* This code will produce output similar to the following:
 * Bruce
 * Alfred
 * Tim
 * Richard
 * Bruce
 * Alfred
 * Tim
 * Richard
 */

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Reference

Tags What's this?: .net (x) action (x) c# (x) delegate (x) Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
See Also Action      Craig Andera ... Charles Miller Jr   |   Edit   |  
This one took me a while to figure out: if you want a delegate that returns void and accepts no argument, just use System.Action (first available in .NET 3.5). Not Action<T>: the one that takes no arguments is not a generic. Which makes sense, but still threw me for a bit.
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker