Delegates

Delegates provide a late binding mechanism in .NET. Late Binding means that you create an algorithm where the caller also supplies at least one method that implements part of the algorithm.

Define delegate types

Let's start with the 'delegate' keyword, because that's primarily what you will use as you work with delegates. The code that the compiler generates when you use the delegate keyword will map to method calls that invoke members of the Delegate and MulticastDelegate classes.

You define a delegate type using syntax that is similar to defining a method signature. You just add the delegate keyword to the definition.

Let's continue to use the List.Sort() method as our example. The first step is to create a type for the comparison delegate:

// From the .NET Core library
// Define the delegate type:
public delegate int Comparison<in T>(T left, T right);

Un delegado es un tipo que representa referencias a métodos con una lista de parámetros determinados y un tipo de valor devuelto.

  • Delegates are like C ++ function pointers, but they are type-safe.

  • Delegates allow methods to be passed as parameters.

  • Delegates can use to define callback methods.

  • Delegates can be chained together; for example, multiple methods can be called on a single event.

  • The methods do not have to exactly match the delegate type.

using System;

namespace Delegates
{
    class Program
    {
        //delegate void MyDelegate();
        delegate void Operation(int number);
        static void Main(string[] args)
        {
            //MyDelegate del = new MyDelegate(SayHello);
            //MyDelegate del2 = SayHello;
            //del2.Invoke();
            //del.Invoke();
            SayHello();

            Operation op = Double;
            ExecuteOperation(2, op);

            op = Tripe;
            ExecuteOperation(8, op);

            Console.ReadLine();
        }

        enum Level
        {
            Low,
            Medium,
            High
        }

        static void SayHello()
        {
            Console.WriteLine($"Hello guys! {Level.High}");
        }

        static void Double(int num)
        {
            Console.WriteLine($"{num} x 2 = {num * 2}");
        }

        static void Tripe(int num)
        {
            Console.WriteLine($"{num} x 3 = {num * 3}");
        }

        static void ExecuteOperation(int num, Operation operation)
        {
            operation(num);
        }
    }
}

Last updated