C# Advanced Methods and Lambdas

Expression-Bodied Methods

In C#, expression-bodied methods are short methods written using a special concise syntax. A method can only be written in expression body form when the method body consists of a single statement or expression. If the body is a single expression, then that expression is used as the method’s return value.

The general syntax is returnType funcName(args...) => expression;. Notice how “fat arrow” notation, =>, is used instead of curly braces. Also note that the return keyword is not needed, since the expression is implicitly returned.

static int Add(int x, int y)
{
return x + y;
}
static void PrintUpper(string str)
{
Console.WriteLine(str.ToUpper());
}
// The same methods written in expression-body form.
static int Add(int x, int y) => x + y;
static void PrintUpper(string str) => Console.WriteLine(str.ToUpper());

Lambda Expressions

A lambda expression is a block of code that is treated like any other value or expression. It can be passed into methods, stored in variables, and created inside methods.

In particular, lambda expressions are useful for creating anonymous methods, methods with no name, to be passed into methods that require method arguments. Their concise syntax is more elegant than declaring a regular method when they are being used as one off method arguments.

int[] numbers = { 3, 10, 4, 6, 8 };
static bool isTen(int n) {
return n == 10;
}
// `Array.Exists` calls the method passed in for every value in `numbers` and returns true if any call returns true.
Array.Exists(numbers, isTen);
Array.Exists(numbers, (int n) => {
return n == 10;
});
// Typical syntax
// (input-parameters) => { <statements> }

Shorter Lambda Expressions

There are multiple ways to shorten the concise lambda expression syntax.

  • The parameter type can be removed if it can be inferred.
  • The parentheses can be removed if there is only one parameter.

As a side note, the usual rules for expression-bodied methods also apply to lambdas.

int[] numbers = { 7, 7, 7, 4, 7 };
Array.Find(numbers, (int n) => { return n != 7; });
// The type specifier on `n` can be inferred based on the array being passed in and the method body.
Array.Find(numbers, (n) => { return n != 7; });
// The parentheses can be removed since there is only one parameter.
Array.Find(numbers, n => { return n != 7; });
// Finally, we can apply the rules for expression-bodied methods.
Array.Find(numbers, n => n != 7);

Methods as Arguments

In C#, one method can take another method as an argument and then call the argument within its body. The argument method should be passed by name only — it should not be called using parentheses.

public static bool IsOdd(int n)
{
return n % 2 == 1;
}
static void Main(string[] args)
{
int[] numbers = {2, 4, 5, 6, 7, 8};
// isOdd is passed by name, not called
int firstOdd = Array.Find(numbers, IsOdd);
Console.WriteLine(firstOdd); // Prints 5
}

Learn more on Codecademy