CSharp Interview Question: What is Action in CSharp

One of my friends called me after his interview as for a developer role in an esteemed organization. One of the question, interviewer asked him,

image

After talking to him, I thought why not to blog about it? I am trying here to use minimum words and optimum code samples can be discussed with interviewer as answer of this question.

Action is type of delegate

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

For example below Action can encapsulates a method taking two integer input parameter and returning void.

 

image

So if you have method like below,

clip_image002

You can encapsulate method Display in Action MyDelegate as below,

image

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

image

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

Action with Anonymous method

You can work with Action and anonymous method as well. You can assign anonymous method to Action as below,

image

Above code will print 9 as output.

Action with Lambda Expression

Like any other delegates, Action can be worked with lambda expression also as below,

image

Above code will also print 9 as output.

Passing Action as input parameter

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

image

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

image

Now you got 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 input parameter to the function.

image

You can call CallingAction method in Main as below,

image

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

image

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

 

5 responses to “CSharp Interview Question: What is Action in CSharp”

  1. Hi,

    Ahh I feel I got every thing about Action keyword.nice one.However I have 2 question

    1.Why Action is introduce if Delegate is already there and
    2.Is there an specefic reason to pass Exception in show and display method

    Thanks
    Anshuman

  2. […] CSharp Interview Question: What is Action in CSharp (Dhananjay Kumar) […]

  3. […] CSharp Interview Question: What is Action in CSharp […]

  4. […] an interesting article today from debugmode.net.  The article describes what the .NET Action<T> class is and how it […]

Leave a comment

Create a website or blog at WordPress.com