Home >Backend Development >C#.Net Tutorial >Explain the concept of delegation in C#

Explain the concept of delegation in C#

PHPz
PHPzforward
2023-08-31 21:17:02957browse

Explain the concept of delegation in C#

If you are a C programmer, you can think of a delegate as a pointer to a function. However, a delegate in C# is more than just a simple function pointer. This article explains the concept of delegation and its use in everyday programming.

Essentially, delegation provides a degree of indirection. They encapsulate a piece of code that can be passed around and executed in a type-safe manner. Rather than performing the behavior immediately, it is contained within an object. You can perform several operations on this object, one of which is to perform a contained behavior.

Using delegates allows us to write higher-order functions, that is, functions that can receive functions as parameters or return functions as return values. A delegate type defines the method signature that a delegate can represent, specifically the method's return type and its parameter types. In the following example, Transformer is a delegate that can represent any method that accepts and returns an integer.

delegate int Transformer(int x);

We can assign any method (including lambda, instance or static methods) to a Transformer instance that satisfies the signature. For example -

Transformer square = x => x * x;
Transformer cube = x => x * x * x;

Console.WriteLine(square(3)); // prints 9
Console.WriteLine(cube(5)); // prints 125

When to use delegation?

Delegates are typically used when the code that wants to perform certain operations does not know the details of those operations but does know the interface for those operations. p>

In programming, we often encounter situations where we need to perform a specific operation, but we do not know in advance which method to call to perform it. Delegates help us solve this problem by replacing the behavior with a delegate and then passing a concrete instance of the delegate with the appropriate behavior as the context and situation requires.

In order for a delegate to do anything, four things need to happen -

1) The delegate type needs to be declared.

A delegate type is essentially the definition of the function it represents, i.e. it consists of the parameters, the types the function will accept, and the return type it returns.

For example, a delegate type representing a method that accepts two numbers as input and returns a number could be declared as -

delegate int Processor(int numOne, int numTwo);

A processor is a type, similar to the types created by classes. To create an instance of this type, you need a method that accepts two numbers as input and returns a boolean value.

2) The code to be executed must be contained in the method.

Define a method with the exact same signature as the above delegate type and do what you want depending on the runtime situation. For example, any of the following methods can be used to create a Processor instance because they all take two numbers and return a number.

static int Add(int numOne, int numTwo){
   Return numOne + numTwo;
}
static int Subtract(int numOne, int numTwo){
   Return numOne - numTwo;
}

3) A delegate instance must be created.

Now that you have a delegate type and a method with the correct signature, you can create an instance of that delegate type. When doing this, we essentially tell the C# compiler to execute this method when the delegate instance is called.

Processor processorOne = new Processor(Add);
Processor processorTwo = new Processor(Subtract);

The above example assumes that the Add and Subtract methods are defined in the same class where we create the delegate instance. If these methods are defined in different classes, we will need an instance of that class.

4) The delegate instance must be called.

This simply calls a method on a delegate instance, unsurprisingly named Invoke. This method on the delegate instance has the same parameter list and return type as specified by the delegate type declaration. Calling Invoke will perform the operation of the delegate instance.

int sum = processorOne.Invoke(3, 5);

However, C# makes it much easier. You can call the delegate instance directly as if it were a method itself. For example,

int difference = processorTwo(10, 6);

Combining and deleting delegates

If we want to perform a series of different operations with a single delegate instance call, C# allows us to do this. system. The delegate type has two static methods called Combine and Remove.

1. Combination

Creates a new delegate with a call list concatenating the call list of the delegate passed as argument. When a new delegate instance is called, all its operations are performed sequentially.

public static Delegate Combine(params Delegate[] delegates); // OR
public static Delegate Combine(Delegate a, Delegate b);

If any operation in the call list throws an exception, it will prevent any subsequent operations from being executed.

2. Delete

Deletes the last occurrence of the delegate call list from the call list of another delegate. Returns a new delegate containing the call list formed by taking the source call list and removing the last occurrence of the value call list.

public static Delegate Remove(Delegate source, Delegate value);

Summary

  • A delegate encapsulates behavior using a specific type and set of parameters, similar to a single-method interface.

  • The type signature described by a delegate type declaration determines which methods can be used to create a delegate instance and the signature of the call.

  • Creating a delegate instance requires the method we want to execute when the delegate is called.

  • Delegate instances are immutable, similar to strings.

  • Each delegate instance contains a call list - a list of operations.

  • Delegate instances can be combined and deleted from each other.

  • ul>

    Example

    Real-time demonstration

    using System;
    class Program{
       delegate int Transformer(int x);
       delegate int Processor(int numOne, int numTwo);
       static void Main(){
          Transformer square = x => x * x;
          Transformer cube = x => x * x * x;
          Console.WriteLine(square(3)); // prints 9
          Console.WriteLine(cube(5)); // prints 125
          Processor processorOne = new Processor(Add);
          Processor processorTwo = new Processor(Subtract);
          int sum = processorOne.Invoke(3, 5);
          Console.WriteLine(sum); // prints 8
          int difference = processorTwo(10, 6);
          Console.WriteLine(difference); // prints 4
       }
       static int Add(int numOne, int numTwo){
          return numOne + numTwo;
       }
       static int Subtract(int numOne, int numTwo){
          return numOne - numTwo;
       }
    }

    Output

    9
    125
    8
    4

The above is the detailed content of Explain the concept of delegation in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete