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

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

Choose your learning style9 modes available
Concept Flow - Expression-bodied methods
Method Declaration
Use => expression
Evaluate expression
Return result
Method call outputs value
An expression-bodied method uses => followed by an expression to return a value directly, making the method concise.
Execution Sample
C Sharp (C#)
int Square(int x) => x * x;

int result = Square(3);
Console.WriteLine(result);
Defines a method that returns the square of a number using expression-bodied syntax and prints the result.
Execution Table
StepActionExpression EvaluatedResultOutput
1Call Square(3)3 * 39
2Return from Square99
3Assign to resultresult = 9
4Print result9
💡 Method call completes and program prints 9, then ends.
Variable Tracker
VariableStartAfter CallFinal
x-33
result--9
Key Moments - 2 Insights
Why is there no curly braces {} in the method?
Expression-bodied methods use => to directly return the expression result, so curly braces and return keyword are not needed (see execution_table step 1).
What happens if the expression is more complex?
The expression after => can be any single expression; it will be evaluated and returned directly, keeping the method concise.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 1, what is the value of the expression evaluated?
A3
B6
C9
D0
💡 Hint
Check the 'Expression Evaluated' column at step 1 in the execution_table.
At which step is the method's return value assigned to the variable 'result'?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for assignment to 'result'.
If the method was written with curly braces and a return statement, how would the execution_table change?
AThe output would change
BSteps would include 'Enter method' and 'Return value' explicitly
CThe expression evaluated would be different
DNo change at all
💡 Hint
Think about how expression-bodied methods simplify the method body compared to traditional syntax.
Concept Snapshot
Expression-bodied methods use => followed by an expression to return a value directly.
They replace curly braces and return statements for simple methods.
Syntax: ReturnType MethodName(params) => expression;
Useful for concise, single-expression methods.
Called like normal methods and return the expression result.
Full Transcript
This example shows how expression-bodied methods work in C#. The method Square takes an integer x and returns x multiplied by itself using the => syntax. When Square(3) is called, the expression 3 * 3 is evaluated to 9, which is returned and assigned to the variable result. Finally, result is printed as 9. Expression-bodied methods let us write short methods without curly braces or return statements, making code cleaner and easier to read.