- Reference
Definition
- Namespace:
- System
- Assembly:
- System.Runtime.dll
- Assembly:
- mscorlib.dll
- Assembly:
- netstandard.dll
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Encapsulates a method that has a single parameter and does not return a value.
generic <typename T>public delegate void Action(T obj);
public delegate void Action<in T>(T obj);
public delegate void Action<T>(T obj);
type Action<'T> = delegate of 'T -> unit
Public Delegate Sub Action(Of In T)(obj As T)
Public Delegate Sub Action(Of T)(obj As T)
Type Parameters
- T
The type of the parameter of the method that this delegate encapsulates.
This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
Parameters
- obj
- T
The parameter of the method that this delegate encapsulates.
Examples
The following example demonstrates the use of the Action<T> delegate to print the contents of a List<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. Note that the example does not explicitly declare an Action<T> variable. Instead, it passes a reference to a method that takes a single parameter and that does not return a value to the List<T>.ForEach method, whose single parameter is an Action<T> delegate. Similarly, in the C# example, an Action<T> delegate is not explicitly instantiated because the signature of the anonymous method matches the signature of the Action<T> delegate that is expected by the List<T>.ForEach method.
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);});void Print(string s){ Console.WriteLine(s);}/* This code will produce output similar to the following:* Bruce* Alfred* Tim* Richard* Bruce* Alfred* Tim* Richard*/
// F# provides a type alias for System.Collections.List<'T> as ResizeArray<'T>.let names = ResizeArray<string>()names.Add "Bruce"names.Add "Alfred"names.Add "Tim"names.Add "Richard"let print s = printfn "%s" s// Display the contents of the list using the print function.names.ForEach(Action<string> print)// The following demonstrates the lambda expression feature of F#// to display the contents of the list to the console.names.ForEach(fun s -> printfn "%s" s)(* This code will produce output similar to the following:* Bruce* Alfred* Tim* Richard* Bruce* Alfred* Tim* Richard*)
Imports System.Collections.GenericClass 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 SubEnd Class' This code will produce output similar to the following:' Bruce' Alfred' Tim' Richard
Remarks
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
. In Visual Basic, it must be defined by the Sub
…End Sub
construct. It can also be a method that returns a value that is ignored.) Typically, such a method is used to perform an operation.
Note
To reference a method that has one parameter and returns a value, use the generic Func<T,TResult> delegate instead.
When you use the Action<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.
#using <System.Windows.Forms.dll>using namespace System;using namespace System::Windows::Forms;public delegate void DisplayMessage(String^ message);public ref class TestCustomDelegate{public: static void ShowWindowsMessage(String^ message) { MessageBox::Show(message); }};int main(){ DisplayMessage^ messageTarget; if (Environment::GetCommandLineArgs()->Length > 1) messageTarget = gcnew DisplayMessage(&TestCustomDelegate::ShowWindowsMessage); else messageTarget = gcnew DisplayMessage(&Console::WriteLine); messageTarget(L"Hello World!"); return 0;}
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); }}
open Systemopen System.Windows.Formstype DisplayMessage = delegate of message: string -> unitlet showWindowsMessage message = MessageBox.Show message |> ignorelet messageTarget = DisplayMessage( if Environment.GetCommandLineArgs().Length > 1 then showWindowsMessage else printfn "%s" )messageTarget.Invoke "Hello, World!"
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
The following example simplifies this code by instantiating the Action<T> delegate instead of explicitly defining a new delegate and assigning a named method to it.
#using <System.Windows.Forms.dll>using namespace System;using namespace System::Windows::Forms;namespace ActionExample{ public ref class Message { public: static void ShowWindowsMessage(String^ message) { MessageBox::Show(message); } };}int main(){ Action<String^>^ messageTarget; if (Environment::GetCommandLineArgs()->Length > 1) messageTarget = gcnew Action<String^>(&ActionExample::Message::ShowWindowsMessage); else messageTarget = gcnew Action<String^>(&Console::WriteLine); messageTarget("Hello, World!"); return 0;}
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); }}
open Systemopen System.Windows.Formslet showWindowsMessage message = MessageBox.Show message |> ignorelet messageTarget = Action<string>( if Environment.GetCommandLineArgs().Length > 1 then showWindowsMessage else printfn "%s" )messageTarget.Invoke "Hello, World!"
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
You can also use the Action<T> delegate with anonymous methods in C#, as the following example illustrates. (For an introduction to anonymous methods, see Anonymous Methods.)
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<T> delegate instance, as the following example illustrates. (For an introduction to lambda expressions, see Lambda Expressions.)
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); }}
open Systemopen System.Windows.Formslet showWindowsMessage message = MessageBox.Show message |> ignorelet messageTarget = Action<string>( if Environment.GetCommandLineArgs().Length > 1 then fun s -> showWindowsMessage s else fun s -> printfn "%s" s )messageTarget.Invoke "Hello, World!"
Imports System.Windows.FormsPublic Module TestLambdaExpression Public Sub Main() Dim messageTarget As Action(Of String) If Environment.GetCommandLineArgs().Length > 1 Then messageTarget = Sub(s) ShowWindowsMessage(s) Else messageTarget = Sub(s) ShowConsoleMessage(s) End If messageTarget("Hello, World!") End Sub Private Function ShowWindowsMessage(message As String) As Integer Return MessageBox.Show(message) End Function Private Function ShowConsoleMessage(message As String) As Integer Console.WriteLine(message) Return 0 End FunctionEnd Module
The ForEach and ForEach methods each take an Action<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.
Extension Methods
GetMethodInfo(Delegate) | Gets an object that represents the method represented by the specified delegate. |
Applies to
See also
- Func<T,TResult>
FAQs
What is an action delegate? ›
C# - Action Delegate
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.
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.
What is the return type of action delegate? ›The Action delegate is generally used for those methods which do not contain any return value, or in other words, Action delegate is used with those methods whose return type is void. It can also contain parameters of the same type or of different types.
What is the difference between func and action delegate in C#? ›If you want to return one result with zero, one or more input parameters, you could use Func Delegate. If you don't want to return result with zero, one or more input parameters, you could use Action Delegate.
How does the delegate process work? ›State delegates go to the national convention to vote to confirm their choice of candidates. But if no candidate gets the majority of a party's delegates during the primaries and caucuses, convention delegates choose the nominee. This happens through additional rounds of voting.
How does delegate work? ›Delegation is not trying to make more work for your team, but to distribute it more efficiently so that tasks get allocated according to skills and workloads. If team members understand this, they'll be happy to contribute to the team effort.
Which of the following statements are true with respect to action delegates? ›Which of the following statements are correct about delegates? Delegates cannot be used to call a static method of a class. Delegates cannot be used to call procedures that receive variable number of arguments. If signatures of two methods are same they can be called through the same delegate object.
What is the difference between func and delegate? ›Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.
How to use a delegate in C#? ›A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.
What are the three roles of the delegate? ›There are three elements of Delegation: Assignment of Responsibility, Grant of Authority, and Creation of Accountability.
What is the difference between delegate and callback? ›
Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.
What are delegate types? ›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.
What is the difference between action T and func T? ›Actions can only take input parameters, while Funcs can take input and output parameters. It is the biggest difference between them. An action can not return a value, while a func should return a value in the other words.
Is there any difference between action and function? ›The main difference between them is that a function can be used inside expressions directly on the screen, while an action can't. But you can still use an function as a regular action in your flows, because the function is still an action.
What is the difference between delegate and lambda in C#? ›Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate. The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
How do you delegate tasks interview answer? ›Select the team member who has the right skill set to complete the task. Explain the directions clearly and what you desire the outcome to look like when they're done. Share with the team member what their responsibility is with the task in terms of the company and why you're giving the task to them.
How do you delegate successfully? ›- Identify work to delegate. Not everything can be delegated. ...
- Practice letting go. ...
- Clarify priorities. ...
- Understand each team member's strengths. ...
- Provide context and guidance. ...
- Invest in training. ...
- Prioritize communication and feedback. ...
- Focus on results.
- About the Five (5) Rights of Delegation.
- Right Task.
- Right Circumstances.
- Right Person.
- Right Direction/Communication.
- Right Supervision/Evaluation.
What is Delegate? A delegate is reference type that basically encapsulates the reference of methods. It is a similar to class that store the reference of methods which have same signature as delegate has.
What is the difference between action and delegates? ›An action is a delegate whose signature has no parameters and has no return value. You can't use Action without using a delegate at the same time, since Action is a specific delegate type.
What is an example of a delegate? ›
Some examples of delegation in the workplace with varying levels of trust and autonomy include: Giving directions to a subordinate and telling them exactly what to do. Assigning someone to compile research, gather feedback, and report back to you so you can make informed decisions.
What was delegate mean? ›verb. delegates; delegated; delegating. Britannica Dictionary definition of DELEGATE. 1. : to give (control, responsibility, authority, etc.) to someone : to trust someone with (a job, duty, etc.)