Delegate, Action, and Func

ipazooki

Mo

Posted on September 20, 2024

Delegate, Action, and Func

Hello everyone, and welcome back to the channel! 🎉 Today, we’re diving into the fascinating world of C# programming, focusing on Delegates, Action, and Func. These are brilliant tools that can boost your coding efficiency and flexibility. So, grab yourself a nice cuppa ☕, and let’s crack on!

What Are Delegates?

A delegate in C# is essentially a type-safe function pointer. 🧐 It allows you to pass methods around just like variables, which makes your code flexible, reusable, and far easier to maintain.

Think of delegates as a contract: any method you pass into the delegate has to follow the rules of the contract, such as the return type and the parameters.

Basic Example of Delegates

Let’s start with a simple example to warm up. We'll create a delegate for a salary calculator.

public delegate double SalaryCalculator(double hoursWorked);

public class Program
{
    public static double ManagerSalary(double hoursWorked) 
    {
        return hoursWorked * 50; // £50 per hour
    }

    public static double EmployeeSalary(double hoursWorked)
    {
        return hoursWorked * 20; // £20 per hour
    }

    public static void Main(string[] args)
    {
        SalaryCalculator calculator = ManagerSalary;
        Console.WriteLine($"Manager's salary: {calculator(40)}");

        calculator = EmployeeSalary;
        Console.WriteLine($"Employee's salary: {calculator(40)}");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we’ve defined a delegate called SalaryCalculator and used it to calculate the salaries for both managers and employees. Neat, right? 😎


Func and Action – The Built-In Delegates 🛠

Instead of defining our own delegate, we can use the built-in Func and Action types that C# provides.

  • Func is perfect for methods that return a value.
  • Action, on the other hand, is used for methods that don’t return anything (i.e., void methods).

Switching to Func

Instead of defining SalaryCalculator manually, we can use Func like this:

public class Program
{
    public static double ManagerSalary(double hoursWorked) 
    {
        return hoursWorked * 50; 
    }

    public static double EmployeeSalary(double hoursWorked)
    {
        return hoursWorked * 20;
    }

    public static void Main(string[] args)
    {
        Func<double, double> calculator = ManagerSalary;
        Console.WriteLine($"Manager's salary: {calculator(40)}");

        calculator = EmployeeSalary;
        Console.WriteLine($"Employee's salary: {calculator(40)}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, Func<double, double> means we’re expecting a method that takes one double parameter and returns a double value.


Using Action

Now, let’s have a look at Action. Unlike Func, Action does not return a value. It’s ideal when you need to perform an operation without expecting anything back.

public class Program
{
    public static void PrintManagerSalary(double hoursWorked) 
    {
        double salary = hoursWorked * 50;
        Console.WriteLine($"Manager's salary: {salary}");
    }

    public static void PrintEmployeeSalary(double hoursWorked)
    {
        double salary = hoursWorked * 20;
        Console.WriteLine($"Employee's salary: {salary}");
    }

    public static void Main(string[] args)
    {
        Action<double> printSalary = PrintManagerSalary;
        printSalary(40); // Manager's salary

        printSalary = PrintEmployeeSalary;
        printSalary(40); // Employee's salary
    }
}
Enter fullscreen mode Exit fullscreen mode

This shows how Action works: it takes an input but doesn’t return anything.


Multicasting Delegates 🌟

One of the coolest features of delegates is multicasting, where you can combine multiple methods into a single delegate call. This can be particularly useful when you need to perform multiple actions in sequence.

Multicasting Example

Let’s extend our salary example to demonstrate multicasting:

public class Program
{
    public static void PrintManagerSalary(double hoursWorked) 
    {
        Console.WriteLine($"Manager's salary: {hoursWorked * 50}");
    }

    public static void LogHoursWorked(double hoursWorked)
    {
        Console.WriteLine($"Hours worked: {hoursWorked}");
    }

    public static void Main(string[] args)
    {
        Action<double> printAndLog = PrintManagerSalary;
        printAndLog += LogHoursWorked;

        printAndLog(40); // Calls both PrintManagerSalary and LogHoursWorked
    }
}
Enter fullscreen mode Exit fullscreen mode

With this, both the PrintManagerSalary and LogHoursWorked methods are called in sequence. How handy is that! 🛠


Wrapping Up 🏁

Delegates, Action, and Func are invaluable tools in C#. They allow you to create more flexible, reusable, and modular code, adhering to good programming principles like the Open-Closed Principle. Delegates let you pass methods around like variables, Action is perfect for methods that don’t return a value, and Func is brilliant when you do need a return value.

Give them a try in your own projects and see how much they can simplify your life as a developer! 🤓

Thanks for tuning in! If you found this helpful, don't forget to give us a thumbs up 👍, subscribe! See you next time! 👋

💖 💪 🙅 🚩
ipazooki
Mo

Posted on September 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related