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
- public class DelegateClass
- {
- public delegate string DelegateDoSomething();
- public string GetSomething()
- {
- throw new NotImplementedException();
- }
- public static void Presenting()
- {
- DelegateClass delegateClass = new DelegateClass();
- DelegateDoSomething delegateDoSomething = new DelegateDoSomething(delegateClass.GetSomething);
- }
- }
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
- public class ActionClass
- {
- public static void Presenting()
- {
- Action<string> DoSomething = delegate
- {
- throw new NotImplementedException();
- };
- }
- }
you can use the Action with anonymous method, take a look at the example
- public static void AnotherPresenting()
- {
- Action<int> ADelegate;
- ADelegate = delegate(int a)
- {
- throw new NotImplementedException();
- };
- ADelegate(1);
- }
You can also define Action with lambda expression, look at the sample
- public static void AnotherPresenting2()
- {
- Action<int> AnAnonymous;
- AnAnonymous = a => Console.Write(2);
- AnAnonymous(2);
- }
Hope you found useful, cheers! More information about Action<T>
- http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
- http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/what-is-action-in-c-sharp/
- http://blogs.msdn.com/b/brunoterkaly/archive/2012/03/02/c-delegates-actions-lambdas-keeping-it-super-simple.aspx