0
0
C Sharp (C#)programming~10 mins

Expression-bodied lambdas in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Expression-bodied lambdas
Define lambda with => expression
Invoke lambda
Evaluate expression
Return result
An expression-bodied lambda uses => to define a function with a single expression that returns a value immediately.
Execution Sample
C Sharp (C#)
Func<int, int> square = x => x * x;
int result = square(3);
Console.WriteLine(result);
Defines a lambda that squares a number and prints the result of squaring 3.
Execution Table
StepActionExpression EvaluatedResult
1Define lambda 'square' as x => x * xx * xLambda stored, no output
2Call square(3)3 * 39
3Print resultConsole.WriteLine(9)Outputs 9
💡 Program ends after printing the result 9
Variable Tracker
VariableStartAfter Step 1After Step 2Final
squarenulllambda function (x => x * x)lambda functionlambda function
resultundefinedundefined99
Key Moments - 2 Insights
Why does the lambda not need curly braces or a return statement?
Because expression-bodied lambdas use a single expression after => which automatically returns its value, as shown in step 1 and 2 of the execution_table.
What happens when we call square(3)?
The expression x * x is evaluated with x=3, resulting in 9, as shown in step 2 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 2?
Aundefined
B9
C3
Dnull
💡 Hint
Check the 'Result' column in row for step 2 in execution_table.
At which step is the lambda function assigned to 'square'?
AStep 3
BStep 2
CStep 1
DBefore Step 1
💡 Hint
Look at the 'Action' column in execution_table for when 'square' is defined.
If we changed the lambda to x => x + 1, what would be the output at step 3?
A4
B9
C3
D1
💡 Hint
Consider the expression evaluated in step 2 and how it affects the printed result in step 3.
Concept Snapshot
Expression-bodied lambdas use => followed by a single expression.
They automatically return the expression's value.
No curly braces or return keyword needed.
Example: Func<int,int> square = x => x * x;
Call like: square(3) returns 9.
Full Transcript
This example shows how expression-bodied lambdas work in C#. First, we define a lambda named 'square' that takes an integer x and returns x multiplied by itself. This is done using the => syntax with a single expression 'x * x'. When we call square(3), the expression evaluates to 9. Finally, we print the result 9 to the console. The lambda does not need curly braces or a return statement because the expression after => is automatically returned.