G
G
Gina Lee2016-04-01 11:08:27
Programming
Gina Lee, 2016-04-01 11:08:27

What do delegates do in C#?

I read about delegates, I realized that this is a type of object, like references to methods. But I still don't get it, for example:

long Sum(List<int> intList)
{
  long result = 0;
  intList.ForEach(delegate(int i) { result += i; });
  result result;
}

what is the delegate doing here?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Alexey Pavlov, 2016-04-01
@Din7

Your task can be done in three ways:
1) create a method that will sum each element of the list into a variable, more precisely, into a class field.

long Result;
long Sum(List<int> intList)
{
    Result = 0;
    intList.ForEach(AddElement);
    return Result;
}

void AddElement(int i)
{
    Result += i;
}

2) In order not to create an "extra" function that is necessary only for a specific task, we can take an anonymous function. Anonymous functions in C# are used with delegates. Additionally, anonymous functions can use closures and there is no need to create an outer field.
long Sum(List<int> intList)
{
    long result = 0;
    intList.ForEach(delegate(int i) { result += i; });
    return result;
}

3) You can take a lambda - in this case, it's "syntactic sugar" - simplifying the creation of a delegate.
long Sum(List<int> intList)
{
    long result = 0;
    intList.ForEach(i => result += i);
    return result;
}

D
Dmitry Kovalsky, 2016-04-01
@dmitryKovalskiy

In this code, a delegate is passed inside the ForEach method, which is called for each element of the intList list. By code, it adds all the elements of the list to the result variable. For a specific problem, there are a dozen simpler and more reliable solutions, but this one looks like shit. Yes, delegates use to pass as a method parameter a reference to a method that satisfies the signature of the delegate.

A
Alexander Kholodovich, 2016-04-01
@kholodovitch

In this case, sums the elements. Increments result by the current element from intList
UPD : in this case it is a reference to an anonymous method

D
Dmitry Eremin, 2016-04-01
@EreminD

Here is a good discussion on the subject.
Download Troelsen's textbook - he quite clearly explains everything in general)

S
Stanislav Makarov, 2016-04-01
@Nipheris

functional object .
As you figure out what it is, you will understand what a delegate is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question