Actions in C# are delegate types representing methods with no return value. They’re used for callbacks and event handling, making code more flexible and maintainable.
Here’s the syntax for declaring and using Actions in C#:
Declaration:
Action<parameter1Type, parameter2Type, ...> actionName;
To declare an Action, use the Action keyword followed by the method’s parameter types. For instance, Action<int, string> represents a method with an int and string parameter and no return value.
Usage:
actionName = methodName; actionName(parameter1Value, parameter2Value, ...);
To use the Action, create an instance and assign a method to it. Then, call the Action with the specified arguments to execute the method.
/* * C# Program to Illustrate Actions */ using System; class Program { static void Main() { Action<int> action1 =(int x) => Console.WriteLine("OUTPUT {0}", x); Action<int, int> action2 =(x, y) => Console.WriteLine("OUTPUT {0} and {1}", x, y); action1.Invoke(1111); action2.Invoke(200, 3000); Console.Read(); } }
1. This C# program illustrates the use of actions.
2. We create two objects ‘action1‘ and ‘action2‘ using Action<int>.
3. Action<int> encapsulates a method with a single parameter and no return value.
4. Action objects return no values. Pass ‘action1‘ and ‘action2‘ variables as arguments to Invoke().
OUTPUT 1111 OUTPUT 200 and 3000
Multicast Actions in C# are delegates that can reference multiple methods at once. They enable calling multiple methods simultaneously using a single delegate instance, achieved by using the “+” operator to add methods and the “-” operator to remove them.
Action actionName = new Action(method1); actionName += new Action(method2); actionName += new Action(method3); // To add a method from the list actionName -= new Action(method2); // To remove a method from the list
In the example, actionName is created using new Action, referring to multiple methods (method1, method2, method3, etc.). += adds methods, and -= removes them. When actionName called, all referenced methods execute in sequence.
- Actions in C# offer benefits such as code reusability by using the same Action with different methods, and decoupling to make the code more maintainable.
- Common use cases include UI event handling, background tasks, and callbacks in asynchronous programming.
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Get Free Certificate of Merit in C# Programming
- Participate in C# Programming Certification Contest
- Become a Top Ranker in C# Programming
- Take C# Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Buy Computer Science Books
- Buy MCA Books
- Practice MCA MCQs