Delegates in C#

Delegates in C#

Hi Everyone, thanks for following up on the next topic I'm writing in C#. Here, we are going to see about Delegates. Let's use a car as an example to learn about the same and I'll try to make things as simpler as possible. Let's dive in.

What are delegates?

Delegates are a type of object that can store and execute one or more methods. Delegates are like pointers or references to methods, which means they can invoke the methods they point to without knowing their details or implementation. Delegates can help you achieve flexibility and modularity in your code by allowing you to pass methods as parameters, return methods as values, or assign methods to variables.

For example, suppose you have a car object that has some methods, such as Start, Stop, Accelerate, Brake, etc. The car object also has a delegate property called Action, which can store and execute any method that has the same signature as the delegate. The signature of the delegate is defined by its return type and parameter list. For example:

// Define a delegate type that can store and execute any method that returns void and takes no parameters
public delegate void CarAction();

// Create a car object that has some methods and a delegate property
public class Car
{
    // Define some methods that have the same signature as the delegate
    public void Start()
    {
        Console.WriteLine("The car starts.");
    }

    public void Stop()
    {
        Console.WriteLine("The car stops.");
    }

    public void Accelerate()
    {
        Console.WriteLine("The car accelerates.");
    }

    public void Brake()
    {
        Console.WriteLine("The car brakes.");
    }

    // Define a delegate property that can store and execute any method that has the same signature as the delegate
    public CarAction Action { get; set; }
}

Now, let’s see how we can use delegates to manipulate the car object in different ways.

Using delegates to assign methods to variables

One way to use delegates is to assign methods to variables of the delegate type. For example:

// Create a new car object
Car car = new Car();

// Assign the Start method to a variable of the delegate type
CarAction start = car.Start;

// Invoke the Start method through the variable
start(); // prints "The car starts."

// Assign the Stop method to another variable of the delegate type
CarAction stop = car.Stop;

// Invoke the Stop method through the variable
stop(); // prints "The car stops."

Using delegates to assign methods to properties

Another way to use delegates is to assign methods to properties of the delegate type. For example:

// Create a new car object
Car car = new Car();

// Assign the Accelerate method to the Action property of the car object
car.Action = car.Accelerate;

// Invoke the Accelerate method through the Action property
car.Action(); // prints "The car accelerates."

// Assign the Brake method to the Action property of the car object
car.Action = car.Brake;

// Invoke the Brake method through the Action property
car.Action(); // prints "The car brakes."

Using delegates to pass methods as parameters

Another way to use delegates is to pass methods as parameters of other methods that accept delegates as arguments. For example:

// Create a new car object
Car car = new Car();

// Define a method that takes a delegate as an argument and invokes it twice
public void DoTwice(CarAction action)
{
    action();
    action();
}

// Pass the Start method as an argument of the DoTwice method
DoTwice(car.Start); // prints "The car starts." twice

// Pass the Stop method as an argument of the DoTwice method
DoTwice(car.Stop); // prints "The car stops." twice

Using delegates to return methods as values

Another way to use delegates is to return methods as values of other methods that return delegates as results. For example:

// Create a new car object
Car car = new Car();

// Define a method that returns a delegate as a result based on a condition
public CarAction GetAction(bool go)
{
    if (go)
    {
        return car.Accelerate;
    }
    else
    {
        return car.Brake;
    }
}

// Call the GetAction method with true as an argument and store the result in a variable of the delegate type
CarAction action1 = GetAction(true);

// Invoke the Accelerate method through the variable
action1(); // prints "The car accelerates."

// Call the GetAction method with false as an argument and store the result in another variable of the delegate type
CarAction action2 = GetAction(false);

// Invoke the Brake method through the variable
action2(); // prints "The car brakes."

Hope this helped you get to know about delegates in .NET and C#. Please comment on any topics about which you want to know. I'll try to write about the same in the upcoming posts.

Did you find this article valuable?

Support Vignesh Ponnuvel by becoming a sponsor. Any amount is appreciated!