Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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;
}
long Sum(List<int> intList)
{
long result = 0;
intList.ForEach(delegate(int i) { result += i; });
return result;
}
long Sum(List<int> intList)
{
long result = 0;
intList.ForEach(i => result += i);
return result;
}
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.
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
Here is a good discussion on the subject.
Download Troelsen's textbook - he quite clearly explains everything in general)
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 questionAsk a Question
731 491 924 answers to any question