What Are C# Lambda Expressions? How Are They Used?
What Are C# Lambda Expressions? How Are They Used?
Examplei => i * iThere is such a usage.
Exampleint square (int i){return i * i;}
delegate(int i){return i * i;}
Here, since the function's return type is not known at the beginning, it is an anonymous function. If we delete the "delegate" part here, we get a lambda function.
(int i){
return i * i;
}
Now we have actually created our anonymous lambda function in a simple way, but as we said at the beginning of the article, they are simplified and anonymous. Now let's simplify this lambda form.
Here, the curly brackets will turn into a lambda expression and our function will take the following form.
(int i ) => return i * i;
Now here, as we mentioned above, the left is the parameter and the right is the expression. Since i*i is already an expression, we can now remove the ";" and "return" words, so our new function will be as follows.
(int i) => i * i
Here, you can enter the input value optionally or not, it is entirely up to you. If you do not want to enter it, you can use it as follows.
i => i * i
Above, we talked about there being a parameter on the left, but not every lambda function/expression requires a parameter and you can also use it as in the following example.
() => function()
Just as there may be no parameter part, more than one parameter value can also be taken as in the following example.
(a,b) => a > b
Yes, friends, I think I have given enough information about Lambda expressions and I want to give a few examples.
Examples
You can check my article about DoTween in Unity here. In that post, I showed the use of Lambda expression to create a Tween simply.
protected void OzelDonmeAnimasyonu(GameObject obje, Vector3 donmeAcisi, float animasyonTamamlanmaSuresi, Ease animasyonYumusatma, RotateMode donmeSekli, System.Action<int> IslemSonucu)
{
obje.transform.DORotate(donmeAcisi, animasyonTamamlanmaSuresi, donmeSekli).SetEase(animasyonYumusatma).OnComplete(() => IslemSonucu(0));
}
void IslemSonucu(int i){
if(i == 0){
Debug.Log("Operation Completed");
}
}
As you can see in the code above, you can use it like this.


Yorum Gönder