Blog

Filter posts by Category Or Tag of the Blog section!

Working with Action in C#

Sunday, 01 September 2013

Action "Encapsulates a method that has a single parameter and does not return a value." ~ MSDN , you don't need to create your own custom delegate to pass a method as a parameter, you can use Action<T> instead. The compiler will figure out the proper types. Action is a type of delegate and takes 0 till 16 parameter with a void value return. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value.

When you are working with delegate (a type that encapsulate a method ), maybe we define something like this

  1.     public class DelegateClass
  2.     {
  3.         public delegate string DelegateDoSomething();
  4.  
  5.         public string GetSomething()
  6.         {
  7.             throw new NotImplementedException();
  8.         }
  9.  
  10.         public static void Presenting()
  11.         {
  12.             DelegateClass delegateClass = new DelegateClass();
  13.             DelegateDoSomething delegateDoSomething = new DelegateDoSomething(delegateClass.GetSomething);
  14.         }
  15.     }

 

By defining the DelegateDoSomething as a delegate we passed the GetSomething() as a parameter,  With Action<T> we can pass method as a parameter easier, take a look this

  1.     public class ActionClass
  2.     {
  3.         public static void Presenting()
  4.         {
  5.             Action<string> DoSomething = delegate
  6.             {
  7.                 throw new NotImplementedException();
  8.             };
  9.         }
  10.     }

 

you can use the Action with anonymous method, take a look at the example

  1.         public static void AnotherPresenting()
  2.         {
  3.             Action<int> ADelegate;
  4.             ADelegate = delegate(int a)
  5.                 {
  6.                     throw new NotImplementedException();
  7.                 };
  8.             ADelegate(1);
  9.         }

You can also define Action with lambda expression, look at the sample

  1.         public static void AnotherPresenting2()
  2.         {
  3.             Action<int> AnAnonymous;
  4.             AnAnonymous = a => Console.Write(2);
  5.             AnAnonymous(2);
  6.         }

 

 

Hope you found useful, cheers! More information about Action<T>

  1. http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
  2. http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/what-is-action-in-c-sharp/
  3. http://blogs.msdn.com/b/brunoterkaly/archive/2012/03/02/c-delegates-actions-lambdas-keeping-it-super-simple.aspx

Category: Software

Tags: C#

comments powered by Disqus