Mastering C# Actions: A Practical Example
In the realm of software development, C# is a powerful and versatile language that enables developers to create robust and efficient applications. One of its key features is the use of actions, which allow for concise and expressive code. Let's dive into a comprehensive example to illustrate the use of C# actions.
Understanding C# Actions
Before we delve into the example, let's briefly understand what actions are in C#. An action is a delegate that represents a method with a void return type and can take up to 16 input parameters. It's often used to pass methods as arguments to other methods, enabling more flexible and dynamic coding.
Syntax
The syntax for defining an action in C# is as follows:

public delegate void Action<in T>(T obj);
Here, T represents the type of the input parameter, and obj is the parameter itself.
Example: Processing a List of Employees
Let's consider a scenario where we have a list of employees, and we want to perform an action on each employee, such as printing their details or updating their salary. We can achieve this using C# actions.
Defining the Employee Class
First, let's define a simple Employee class:

public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }
public override string ToString()
{
return $"Name: {Name}, Salary: {Salary}";
}
}
Creating a List of Employees
Next, let's create a list of employees:
List<Employee> employees = new List<Employee>
{
new Employee { Name = "John Doe", Salary = 50000 },
new Employee { Name = "Jane Smith", Salary = 55000 },
new Employee { Name = "Mike Johnson", Salary = 60000 }
};
Defining Actions on Employees
Now, let's define two actions that we can perform on employees:
- PrintEmployeeDetails: This action will print the details of an employee.
- IncreaseSalary: This action will increase the salary of an employee by a specified amount.
The C# code for these actions might look like this:

Action<Employee> PrintEmployeeDetails = (employee) =>
{
Console.WriteLine(employee);
};
Action<Employee> IncreaseSalary = (employee, amount) =>
{
employee.Salary += amount;
};
Using Actions to Process Employees
Finally, let's use these actions to process our list of employees. We can use the ForEach method of the List<T> class, which takes an Action<T> as an argument:
employees.ForEach(PrintEmployeeDetails);
employees.ForEach(IncreaseSalary);
In this example, we first print the details of each employee, then increase their salary by a specified amount.
Conclusion
C# actions provide a powerful and flexible way to pass methods as arguments to other methods. In this article, we've seen how actions can be used to perform operations on a list of employees, demonstrating their practical use in real-world scenarios.





















