An Action
(and it's sibling Action<T>
) is a pre-defined delegate
type in the .NET framework. It exists to provide a standard interface for function calls that do not return a value. There is a cousin delegate
type called Func<TResult>
which returns a TResult
generic type.
These delegates com in two flavors, generic and non-generic. The non-generic Action
takes no parameters, and returns void
. The generic Action
can take up to 16 parameters of generic types as parameters (but also doesn't return a value)
The same holds true for Func<TResult>
, except all versions are generic. It can take 0 to 16 generic parameters and returns a generic type.
In the "old days" to use a delegate, you would have to first define the delegate
, then use it. Like this:
public delegate void ShowValue();
Then use it like so...
ShowValue showMethod = testName.DisplayToWindow;
showMethod();
But with an Action, you just have to do this:
Action showMethod = delegate() { testName.DisplayToWindow();} ;
showMethod();
Another nice thing is that anonymous lambda's are by their nature Action
or Func<TResult>
compatible, so you can just do this:
Action showMethod = () => testName.DisplayToWindow();
showMethod();
This has a lot of nice convenience, but more importantly Microsoft created these delegate
types so that their own framework would be able to use a standard interface. You can take advantage of these types in your own code as well.