Hello everyone, in this article we will talk about “Action” a readymade delegate.
Action is just another delegate that takes some parameters and doesn’t return a value. So when do you want to execute some method which doesn’t return any value then rather creating your own delegate. .Net framework provides us an Action Delegate. Please have a look on below image –
So let’s take an example of using Action –
Action using Anonymous Functions-
Action is just another delegate that takes some parameters and doesn’t return a value. So when do you want to execute some method which doesn’t return any value then rather creating your own delegate. .Net framework provides us an Action Delegate. Please have a look on below image –
So In general Action is a delegate -
- Which is contra variant ( in parameter will discuss this in next articles )
- Which takes 1 to 16 parameters but do not return any value.
So let’s take an example of using Action –
private static void MyActionMethod() { Action obj = new Action(MyDummyMethod); //Synchronous way obj.Invoke(); //Asynchronous way obj.BeginInvoke(null, null); Console.ReadLine(); // You can call it as asynchronous way because this is just a delegate }
Cool J So we saw in this example we can invoke an action as a synchronous way as well as asynchronous way because Action is none other than a delegate.
Action using Lambda Expressions –static Action<string> MyActionUsingLambda = str => Console.WriteLine(str); MyActionUsingLambda("saurabh");
Action using Anonymous Functions-
Action<string> MyActionUsingAnounymous = delegate(string str) { Console.WriteLine(str); }; public void ActionUsingAnonymousMethod(string str) { MyActionUsingAnounymous(str); }
So that was all about Action in C#.
Hope you like reading the article. Please inbox me in
case of any confusion you have.
Happy CodingJ