Delegates Part 4: Lambda Expressions

Using a Lambda Expression is a great way to convert a method into a line of code. Let’s use one of the method examples from my previous articles on delegates, and convert it to a Lambda Expression.Here we have a return type Functional delegate that tak…


This content originally appeared on Level Up Coding - Medium and was authored by Jared Amlin

Using a Lambda Expression is a great way to convert a method into a line of code. Let’s use one of the method examples from my previous articles on delegates, and convert it to a Lambda Expression.

Here we have a return type Functional delegate that takes in a string value and spits out an int value.

private Func<string, int> StringLength;

The String Length delegate variable is assigned the value of the Get String Length method. The console is then sent a message to return the value of the string with a given argument of my name, Jared.

StringLength = GetStringLength;
Debug.Log("The string count is " + StringLength("Jared"));

The method takes in a string parameter and returns the length of it.

private int GetStringLength(string text)
{
return text.Length;
}

Let’s convert this to a lambda expression by assigning the String Length variable to the lambda rather than the method. I will comment out the previous assignment for reference.

To declare a lambda expression, you first provide the parameters for the delegate. In this case, it’s a string value. I am going to use the variable name text here, because that is what I used in the original method. Next, use the lambda operator, which is an equals sign followed by a right angle bracket =>. The lambda operator means “go to”. Then I am ‘going to’ the command that was in the method, which is returning the length of the string being passed in.

//StringLength = GetStringLength;
StringLength = (text) => text.Length;
Debug.Log("The string count is " + StringLength("Jared"));

I can now comment out the existing Get String Length method, because the functionality of the lambda expression will be identical.

//private int GetStringLength(string text)
//{
//return text.Length;
//}

Here in the console, the string length of Jared is 5.

Practice: Delegates with Lambda Expressions

Create a void type delegate with parameters that calculates the sum of two numbers.

Here is an action delegate that takes in two integer values as parameters in order to calculate the sum.

private Action<int, int> Sum;

Here is the method that will be used to work out the logic before converting it to a lambda expression.

private void CalculateSum(int a, int b)
{
var SumTotal = a + b;
Debug.Log("The Calculated Sum is " + SumTotal);
}

The Sum action is assigned to the Calculate Sum method, and then on the following line the needed parameter values are entered.

Sum = CalculateSum;
if (Sum != null)
Sum(7, 7);

The values of 7 and 3 are added together and printed as 10 in the console.

The dedicated method is commented out, and now the Sum action delegate is converted to use a lambda expression. The int values are changed to 7 and 7 to yield a different result.

Sum = (a, b) => { var SumTotal = a + b; Debug.Log("The Calculated Sum is " + SumTotal); };
if (Sum != null)
Sum(7, 7);

Now the console tells me that the Sum is 14.

Create a void type delegate with NO parameters that tells the name of a game object.

Here is a new action delegate with no parameters that will print the name of the game object the script is attached to.

private Action onGetObjectName;

Here is a method to print the name of the game object.

private void GetName()
{
Debug.Log("This object name is " + this.gameObject.name);
}

The onGetObjectName is assigned to the GetName method. To run it with no parameters, just call it the delegate like a normal method.

onGetObjectName = GetName;
if (onGetObjectName != null)
onGetObjectName();

Here you can see the object this script is attached to is called Delegate Manager.

The method is removed and converted to use a lambda expression instead. Because this delegate has no parameters, the method signature is declared with the empty brackets.

onGetObjectName = () => Debug.Log("This object name is " + this.gameObject.name);
if (onGetObjectName != null)
onGetObjectName();

Just like with the dedicated method, the name of the object is printed in the console.

Create a return type delegate with NO parameters that calculates the length of a game object name.

This example will be similar to the one where I return the length of my name, Jared. The only difference will be returning the length of the name of the game object the script it attached to.

For a return type delegate, let’s bring the Func! Because it is a return type, we need to specify the value type being returned, which in this case is an int value.

private Func<int> onNameLength;

Here is the method to return the name length of the object this script is attached to.

private int ReturnObjectNameLength()
{
var count = this.gameObject.name.Length;
Debug.Log("character count is " + count);
return count;
}

The delegate variable is assigned to the method and called with no parameters.

onNameLength = ReturnObjectNameLength;
if (onNameLength != null)
onNameLength();

The console tells me that the character count is 15, which represents the DelegateManager object.

Now let’s remove the dedicated method and convert this to a lambda expression. Now send the length of the name to the console from here.

onNameLength = () => this.gameObject.name.Length;
if (onNameLength != null)
{
int characterCount = onNameLength();
Debug.Log("The character count of this object is " + characterCount);
}

Again, the character count is 15.

Create a return type delegate with parameters that returns the Sum of two numbers.

This example is the same as the previous one that calculates the sum of two numbers, only using a return type delegate rather than a void type.

Here is a return type delegate that takes in two int values, and returns an int value.

private Func<int, int, int> onReturnSum;

The method here takes in the two values and adds them together. The sum is stored in the total variable, which is sent to the console.

private int ReturnSumValue(int a, int b)
{
var total = a + b;
Debug.Log("The total Sum is " + total);
return a + b;
}

Here 12 and 3 are entered to satisfy the parameters.

onReturnSum = ReturnSumValue;
if (onReturnSum != null)
onReturnSum(12, 3);

The console tells me the sum of those numbers is 15.

Now let’s convert this to a lambda expression.

onReturnSum = (a, b) => a + b;
if (onReturnSum != null)
Debug.Log("The total sum is " + onReturnSum(10, 3));

Now with new values of 10 and 3, the console tells me the sum is 13. Notice that when doing it this way you don’t actually need to use the return keyword, even though the delegate is a return type.

If you want to add further logic, you can do so, but then will need to use the return keyword to return a value.

onReturnSum = (a, b) => { var totalSum = a + b; Debug.Log("The total sum is " + totalSum); return totalSum; };
if (onReturnSum != null)
onReturnSum(12, 10);

Here the values of 12 and 10 are 22 when added together.

I hope to enjoyed this write up on lambda expressions and thanks for reading!


Delegates Part 4: Lambda Expressions was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Jared Amlin


Print Share Comment Cite Upload Translate Updates
APA

Jared Amlin | Sciencx (2022-12-04T18:42:46+00:00) Delegates Part 4: Lambda Expressions. Retrieved from https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/

MLA
" » Delegates Part 4: Lambda Expressions." Jared Amlin | Sciencx - Sunday December 4, 2022, https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/
HARVARD
Jared Amlin | Sciencx Sunday December 4, 2022 » Delegates Part 4: Lambda Expressions., viewed ,<https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/>
VANCOUVER
Jared Amlin | Sciencx - » Delegates Part 4: Lambda Expressions. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/
CHICAGO
" » Delegates Part 4: Lambda Expressions." Jared Amlin | Sciencx - Accessed . https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/
IEEE
" » Delegates Part 4: Lambda Expressions." Jared Amlin | Sciencx [Online]. Available: https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/. [Accessed: ]
rf:citation
» Delegates Part 4: Lambda Expressions | Jared Amlin | Sciencx | https://www.scien.cx/2022/12/04/delegates-part-4-lambda-expressions/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.