The short answer
In C#, => is the lambda arrow. It separates the parameters of an anonymous function from its body. The expression x => x * 2 reads as “x goes to x times 2”, and it describes a function that takes x and returns x * 2.
The arrow has two other common uses in modern C#: expression-bodied members and switch expressions. This page is about C#. C++ uses different syntax for the same idea, and a comparison is shown near the end.
Lambda expressions
A lambda expression creates an anonymous function, so you can pass it somewhere without declaring a method first:
using System;
Func<int, int> doubleIt = x => x * 2;
Console.WriteLine(doubleIt(5)); // 10
Func<int, int> is a delegate type for a function that takes an int and returns an int.
A lambda with several parameters puts them in parentheses. A body with more than one statement goes in braces:
using System;
Func<int, int, int> add = (a, b) => a + b;
Func<int, string> describe = n =>
{
if (n < 0) return "negative";
return "zero or positive";
};
Console.WriteLine(add(2, 3)); // 5
Console.WriteLine(describe(-4)); // negative
Lambdas are often used with LINQ, the query methods available on collections:
using System;
using System.Collections.Generic;
using System.Linq;
var numbers = new List<int> { 1, 2, 3, 4 };
var evens = numbers.Where(n => n % 2 == 0);
foreach (var n in evens)
{
Console.WriteLine(n); // 2, then 4
}
Expression-bodied members
C# 6 added a shorter form for members whose body is a single expression. The arrow replaces the braces and the return keyword:
class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public int Area() => Width * Height;
}
Switch expressions
C# 8 added switch expressions. Each arm uses => to separate a pattern from the result it produces:
string size = n switch
{
1 => "small",
2 => "medium",
_ => "large",
};
Compared with C++
C++ has no => operator. A C++ lambda starts with a capture list in square brackets, and its parameters follow in parentheses:
#include <iostream>
int main() {
auto double_it = [](int x) { return x * 2; };
std::cout << double_it(5) << "\n"; // 10
}
A few differences are worth knowing:
- A C++ lambda lists the outside variables it uses in its capture list, such as
[ ],[x]or[&x]. A C# lambda can use outside local variables directly, and the compiler handles that for you. - In C++,
->introduces a trailing return type, as in[](int x) -> int { return x * 2; }. In C#,=>marks the start of a lambda body. - Writing
x => x * 2in C++ is a syntax error, so the two languages are not interchangeable in this respect.
Quick answer
In C#, => is the lambda arrow. It appears in lambda expressions such as x => x * 2, in expression-bodied members and in switch expressions. C++ has no => operator, and it writes lambdas with a capture list instead.