Answer the question
In order to leave comments, you need to log in
Where, when and how best to use lambda expressions?
Prompt) Here I read Richter, I raise the level so to speak. The question is, in what cases can lambda expressions be used, and in which cases can a separate method or delegate be used? As far as I understand, complex calculations or algorithms are better to be sent to a method? Are there specific conditions for this part? Or here based on the subjective view of the programmer. Share your experience)
Answer the question
In order to leave comments, you need to log in
In short, use lambdas until you get confused about them. As you get confused, you will understand the answer to your question.
The canonical use of lambda functions is to capture variables in the namespace of the surrounding function. Read about closure.
I use lambda expressions in two cases:
- when it's really an "expression" i.e. the whole calculation fits into one formula;
- when it is necessary to use the values of the variables of the current method for calculations.
At the same time, I remember that "under the carpet" the compiler will create a separate class for each context with a lambda expression, and the captured variables will be fields of this class (and the lambda expression itself will be its method). Moreover, they will be used as fields, not only for the code that calculates this expression, but for all work with these variables. So, if in a particular place you have to think about efficiency, then you need to weigh everything.
You have a "main" function that does:
1. I do something once
2. I do something twice
3. I do something three times.
"I do something two" has different implementations, in one case you do one thing, in the other another. You can write several options for implementing the main function for each such implementation, and steps #1 and #3 will always be identical in it. In order not to repeat, you take step #2 into an anonymous function, and now you can pass it as a parameter to the main function, thus. you made the code more concise.
For example, you need to write 4 methods that do fairly similar actions. Let it be arithmetic operations with int. But why write the implementation of all methods, if you can pass different actions to just one lambda:
class Program
{
static void Main ( string [ ] args )
{
int i;
i = SomeAction ( 10 , 20 , ( a , b ) => a + b );
i = SomeAction ( 10 , 20 , ( a , b ) => a - b );
i = SomeAction ( 10 , 20 , ( a , b ) => a / b );
i = SomeAction ( 10 , 20 , ( a , b ) => a * b );
}
static int SomeAction( int a1 , int a2 , Func<int,int,int> func )
{
return func ( a1 , a2 );
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question