How is the usage of action in C#?
In C#, an Action is a delegate type that can be used to reference methods that do not return a value. Actions can take between 0 and 16 parameters, and do not return any value.
The usage of “Action” is as follows:
- Declare an Action delegate type.
- Action called action;
Action with integer called actionWithInt;
Action with string and integer called actionWithStringAndInt; - Instantiate an Action object and assign it to a delegate variable:
- Action without parameters is defined as a function that outputs a message to the console.
- Call to Action:
- action(); // Output: Action without any parameters
actionWithInt(10); // Output: Action with integer parameter: 10
actionWithStringAndInt(“Hello”, 20); // Output: Action with string and integer parameters: Hello, 20
Actions can be used to perform any operation that does not return a value, such as printing messages or updating states. It is a versatile type of delegate that is very convenient for handling different parameters and function signatures.