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:
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:
- It returns no value.
- 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.
So if you have a method like below:
You can encapsulate the method Display in Action MyDelegate as below:
An Action with one input parameter is defined in the System namespace as below:
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:
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:
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:
And two functions called Display and Show to display Name and RollNumber of Student.
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.
You can call the CallingAction method in Main as below:
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:
I hope now you are able to answer what an Action is in simple words. I hope this post is useful. Thanks for reading.