Sobes.tech
Junior — Middle

Can you name the main types of delegates used in programming languages?

sobes.tech AI

Answer from AI

In C#, delegates are types that represent references to methods with a specific signature. The main types of delegates:

  • Single-cast delegates — refer to one method.
  • Multicast delegates — can contain a list of methods that are called sequentially.

Additionally, there are standard generic delegates:

  • Action — a delegate that represents a method with no return value and 0 or more parameters.
  • Func<TResult> and Func<T1, TResult> etc. — delegates that return a value and can accept parameters.
  • Predicate<T> — a delegate that takes one parameter and returns a bool.

Example of declaring and using a delegate:

public delegate int Operation(int x, int y);

Operation add = (a, b) => a + b;
int result = add(3, 4); // 7

Multicast delegate:

Operation op = add;
op += (a, b) => a * b;

foreach (Operation del in op.GetInvocationList()) {
    Console.WriteLine(del(3, 4));
}

Thus, the main types of delegates are single-cast, multicast, and the standard generic delegates Action, Func, and Predicate.

Can you name the main types of delegates used in… - sobes.tech