Programming

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,

What is Action

 

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.

imgp10

So if you have method like below,

imgp9

You can encapsulate method Display in Action MyDelegate as below,

imgp8

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

imgp7

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,

imgp6

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,

imgp5

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

imgp4

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

imgp3

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.

imgp2

You can call CallingAction method in Main as below,

imgp1

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.

output action

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

 

Previous ArticleNext Article