wingman007

LambdaFormsInC#–ExpressionVsStatementBodies

Oct 19th, 2025
1,763
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.49 KB | Software | 0 0
  1. // ✅ Named method – complex logic
  2. static int Factorial(int n)
  3. {
  4.     int result = 1;
  5.     for (int i = 2; i <= n; i++)
  6.         result *= i;
  7.     return result;
  8. }
  9.  
  10. // ✅ Named expression-bodied method – simple logic
  11. static int Square(int x) => x * x;
  12.  
  13. // ✅ Anonymous lambda – expression-bodied
  14. Func<int, int> addOne = x => x + 1;
  15.  
  16. // ✅ Anonymous lambda – statement-bodied
  17. Func<int, int> addOneVerbose = x =>
  18. {
  19.     int y = x + 1;
  20.     return y; // must return explicitly
  21. };
  22.  
Advertisement
Add Comment
Please, Sign In to add comment