What is Action in C#?


One of my friends called me after his interview for a developer role in an esteemed organization. One of the questions the interviewer asked him was:

ActionCsharp1.gif

After talking to him, I thought why not blog about it? I am trying here to use a minimum of words and optimum code samples to discuss the answer of this interview question.

An Action is a type of delegate:

  1. It returns no value.
  2. It may take 0 parameter to 16 parameters.

For example the following Action can encapsulate a method taking two integers as input parameters and returning void.

ActionCsharp2.gif

So if you have a method like below:

ActionCsharp3.gif

You can encapsulate the method Display in Action MyDelegate as below:

ActionCsharp4.gif

An Action with one input parameter is defined in the System namespace as below:

ActionCsharp5.gif

Where in T is a type of input parameter and a T object is a value passed for the parameter.

Action with Anonymous method

You can work with Action and anonymous methods as well. You can assign an anonymous method to an Action as below:

ActionCsharp6.gif

The above code will print 9 as output.

Action with Lambda Expression

Like any other delegates, an Action can be created with a lambda expression also, as below:

ActionCsharp7.gif

The above code will also print 9 as output.

Passing Action as input parameter

You can pass an Action as a parameter of a function also. Let us say you have a class:

ActionCsharp8.gif

And two functions called Display and Show to display Name and RollNumber of Student.

ActionCsharp9.gif

Now you have a function where you need to pass either Display or Show. Or in other words you need to pass any function with the same signature of Display or Show. In that case you will be passing a delegate as an input parameter to the function.

ActionCsharp10.gif

You can call the CallingAction method in Main as below:

ActionCsharp11.gif

Above we are creating an instance of the Student class and one by one passing to the Display function and the Show function as input parameter to the CallingAction function. In the CallingAction function, we are printing the name of the function being passed as input parameter. On running you will get the following output:

ActionCsharp12.gif

I hope now you are able to answer what an Action is in simple words. I hope this post is useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all