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,
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
- It returns no value.
- It may take 0 parameter to 16 parameters.
For example below Action can encapsulates a method taking two integer input parameter and returning void.
So if you have method like below,
You can encapsulate method Display in Action MyDelegate as below,
An Action with one input parameter is defined in System namespace as below,
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,
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,
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
And two functions called Display and Show to display Name and RollNumber of Student.
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.
You can call CallingAction method in Main as below,
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.
I hope now you would be able to answer what is Action in simple words. I hope this post is useful. Thanks for reading.
Follow @debug_mode
Leave a Reply