Action Delegates

Introduction

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe and secure. The type of a delegate is defined by the name of the delegate. We know there are two types of delegates namely SingleCast delegates and Multicast delegates.

But there are 3 special types of delegates available in C#. They are called Action, Func and Predicate. Let"s have a look at Action delegates and how to use them.

Action Delegate

This is a special kind of delegate that points to methods that don't return a value. In C# terms, it points to void methods. Remember that the point of the Action delegate family was to be able to do an “action” on an item, with no return results. Thus Action delegates can be used to represent most methods that take 0 to 16 arguments but return void. When you use the Action<T> delegate, you do not need 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 ShowMessageBox method to its delegate instance.

  1. public static void Main()  
  2. {  
  3.      Action<string> Target;  
  4.      if (Environment.GetCommandLineArgs().Length > 1)  
  5.          Target = ShowMessageBox;  
  6.      else  
  7.          Target = Console.WriteLine;  
  8.      messageTarget("Magic of Action delegate");  
  9.  }  
  10.  private static void ShowMessageBox(string message)  
  11.  {  
  12.      MessageBox.Show(message);  
  13.  }  
Anonymous Method Usage

Most often, Action delegates are used with anonymous types.
  1. var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name = "Bubu" } };  
  2. obj.ForEach(data=> Console.WriteLine(data));  
If you see the documentation cache, you will notice that the ForEach method expects an action delegate. This is one practical use of action delegates. You can create your own. Let"s see one example:
  1. public static void PrintLine<T>(this T source, Action<T> value)  
  2. {  
  3.     value(source);  
  4. }  
And then you can use this extension method to any of your objects. Let"s print an object using this method; see the following:

person.PrintLine(data => Console.WriteLine(data.ID));

I hope this helps. 

 

Up Next
    Ebook Download
    View all
    Learn
    View all