ZetCode

C# expression

last modified November 6, 2026

In this article we show the kinds of expressions in C#.

An expression is a piece of code that evaluates to a value. It is made of operands, such as literals, variables, and method calls, and operators that combine them. 2 + 3, name.Length, and x > 0 are expressions.

A statement is a complete instruction, such as a declaration, an if, or a loop. It does not have a value.

Func<int, int> square = x => x * x;
Console.WriteLine("falcon");

The first line is a declaration statement whose right side is a lambda expression. The second line is an expression statement: a method call used as a statement, whose result, if any, is discarded.

Besides the usual arithmetic, comparison, and logical operators, C# has several special kinds of expressions:

Expressions can also be the bodies of methods and other members.

Lambda expressions

A lambda expression is an anonymous function. The => operator separates the parameters from the body.

Program.cs
int[] vals = [1, -2, 3, 4, 0, -3, 2, 1, 3];

var positive = Array.FindAll(vals, e => e > 0);
Console.WriteLine(string.Join(" ", positive));

var square = (int x) => x * x;
Console.WriteLine(square(7));

var greet = (string name = "guest") => $"Hello, {name}!";
Console.WriteLine(greet());
Console.WriteLine(greet("Anna"));

The lambda e => e > 0 is passed to Array.FindAll as the condition for the elements to keep. The compiler infers the type of e from the array.

var square = (int x) => x * x;

A lambda with typed parameters has a natural type, so it can be assigned to var. Here it becomes a Func<int, int>.

var greet = (string name = "guest") => $"Hello, {name}!";

Since C# 12, lambda parameters can have default values.

$ dotnet run
1 3 4 2 1 3
49
Hello, guest!
Hello, Anna!

Query expressions

A query expression uses LINQ keywords such as from, where, orderby, and select to filter and transform data.

Program.cs
int[] vals = [-2, 4, 6, -1, 2, 0, 1, -3, -4, 2, 3, 8];

var evens =
    from val in vals
    where val % 2 == 0
    orderby val
    select val * 10;

Console.WriteLine(string.Join(" ", evens));

var same = vals.Where(val => val % 2 == 0).OrderBy(val => val).Select(val => val * 10);
Console.WriteLine(string.Join(" ", same));

The query selects the even numbers, sorts them, and multiplies each by ten.

var same = vals.Where(val => val % 2 == 0).OrderBy(val => val).Select(val => val * 10);

The compiler translates a query expression into calls of LINQ methods with lambdas. This method syntax gives the same result.

$ dotnet run
-40 -20 0 20 20 40 60 80
-40 -20 0 20 20 40 60 80

Switch expressions

A switch expression compares a value against patterns and evaluates to the result of the first arm that matches. Unlike the switch statement, it produces a value.

Program.cs
int age = 23;
string name = "Peter";
List<string> colors = ["blue", "khaki", "orange"];
int[] nums = [1, 2, 3, 4, 5];

Console.WriteLine(Check(age));
Console.WriteLine(Check(name));
Console.WriteLine(Check(colors));
Console.WriteLine(Check(nums));
Console.WriteLine(Check(3.5));

Console.WriteLine(Classify(-4));
Console.WriteLine(Classify(0));
Console.WriteLine(Classify(5));
Console.WriteLine(Classify(15));

static string Check(object val) => val switch
{
    int => "integer",
    string => "string",
    List<string> => "list of strings",
    Array => "array",
    _ => "unknown"
};

static string Classify(int n) => n switch
{
    < 0 => "negative",
    0 => "zero",
    > 0 and < 10 => "small",
    _ => "large"
};

Check uses type patterns to name the type of its argument. The discard pattern _ matches everything else.

< 0 => "negative",
0 => "zero",
> 0 and < 10 => "small",

Classify uses relational patterns, combined with and. The arms are tried in order.

$ dotnet run
integer
string
list of strings
array
unknown
negative
zero
small
large

With expressions

A with expression creates a copy of a value with some properties changed. It works with records, structs, and anonymous types.

Program.cs
var p1 = new Point(0, 0);
var p2 = p1 with { Y = 3 };

Console.WriteLine(p1);
Console.WriteLine(p2);

var pos = new Position(1.5, 2.5);
var moved = pos with { Lat = 10 };
Console.WriteLine(moved);

var user = new { Name = "Anna", Age = 31 };
var older = user with { Age = 32 };
Console.WriteLine(older);

record Point(int X, int Y);
record struct Position(double Lat, double Lon);

p2 is a copy of p1 with a new Y coordinate. The original is not modified.

var moved = pos with { Lat = 10 };

A record struct supports with in the same way.

var older = user with { Age = 32 };

Anonymous types are immutable, so with is the way to get a modified copy.

$ dotnet run
Point { X = 0, Y = 0 }
Point { X = 0, Y = 3 }
Position { Lat = 10, Lon = 2.5 }
{ Name = Anna, Age = 32 }

Interpolated string expressions

An interpolated string, prefixed with $, contains expressions in braces. Their values are formatted and inserted into the string.

Program.cs
int x = 5;
int y = 6;
double price = 1234.5678;

Console.WriteLine($"{x} * {y} = {x * y}");
Console.WriteLine($"Price: {price:F2}, padded: [{x,5}] [{x,-5}]");
Console.WriteLine($"{(x > y ? "x is bigger" : "y is bigger")}");

string json = $$"""{"x": {{x}}, "y": {{y}}}""";
Console.WriteLine(json);

{x * y} evaluates the multiplication.

Console.WriteLine($"Price: {price:F2}, padded: [{x,5}] [{x,-5}]");

A format string follows a colon, and an alignment follows a comma. A positive alignment pads on the left, a negative one on the right.

Console.WriteLine($"{(x > y ? "x is bigger" : "y is bigger")}");

A conditional expression must be in parentheses, because its colon would otherwise start a format string.

string json = $$"""{"x": {{x}}, "y": {{y}}}""";

In a raw interpolated string with two dollar signs, expressions use double braces and single braces are plain text. This is handy for JSON.

$ dotnet run
5 * 6 = 30
Price: 1234.57, padded: [    5] [5    ]
y is bigger
{"x": 5, "y": 6}

Conditional, null-coalescing, and throw expressions

The conditional operator ?: chooses between two values. The null-coalescing operator ?? gives a fallback for null.

Program.cs
int temp = 27;
string? nick = null;
string[]? items = null;

string feel = temp > 25 ? "hot" : "fine";
Console.WriteLine(feel);

Console.WriteLine(nick ?? "no nickname");
Console.WriteLine(items?.Length ?? 0);

nick ??= "Johnny";
Console.WriteLine(nick);

int Half(int n) => n % 2 == 0 ? n / 2 : throw new ArgumentException($"{n} is odd");

Console.WriteLine(Half(10));

try
{
    Console.WriteLine(Half(7));
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

temp > 25 ? "hot" : "fine" evaluates to the first value when the condition is true and to the second otherwise.

Console.WriteLine(items?.Length ?? 0);

The null-conditional operator ?. gives null when items is null, and ?? turns that into 0.

nick ??= "Johnny";

??= assigns only when the variable is null.

int Half(int n) => n % 2 == 0 ? n / 2 : throw new ArgumentException($"{n} is odd");

A throw expression can appear in a conditional expression, after ??, and in an expression-bodied member.

$ dotnet run
hot
no nickname
0
Johnny
5
7 is odd

Collection expressions

A collection expression, added in C# 12, creates an array, list, span, or other collection from elements in square brackets.

Program.cs
int[] a = [1, 2, 3];
List<int> b = [4, 5];
Span<int> c = [6, 7];

int[] all = [.. a, .. b, .. c, 8];
Console.WriteLine(string.Join(" ", all));

Console.WriteLine(string.Join(" ", all[^3..]));
Console.WriteLine(all[^1]);

string[] empty = [];
Console.WriteLine(empty.Length);

The same syntax initializes an array, a list, and a span. The target type decides what is created.

int[] all = [.. a, .. b, .. c, 8];

The spread element .. inserts all elements of another collection.

Console.WriteLine(string.Join(" ", all[^3..]));

Index and range expressions select elements: ^3.. is the range of the last three elements and ^1 is the last element.

$ dotnet run
1 2 3 4 5 6 7 8
6 7 8
8
0

Expression-bodied members

A method, constructor, property, indexer, operator, or finalizer whose body is a single expression can be written with => instead of a block.

Program.cs
var u = new User("John Doe", "gardener");
Console.WriteLine(u);
Console.WriteLine(u.Initials);
Console.WriteLine(u[0]);

class User
{
    public User(string name, string occupation) =>
        (Name, Occupation) = (name, occupation);

    public string Name { get; set; }
    public string Occupation { get; set; }

    public string Initials => string.Concat(Name.Split(' ').Select(w => w[0]));

    public char this[int i] => Name[i];

    public override string ToString() => $"{Name} is a {Occupation}";
}

The class uses an expression body for each kind of member.

public User(string name, string occupation) =>
    (Name, Occupation) = (name, occupation);

The constructor assigns both properties at once with a tuple assignment.

public string Initials => string.Concat(Name.Split(' ').Select(w => w[0]));

A read-only property with an expression body is computed each time it is read.

public char this[int i] => Name[i];

The indexer returns the character of the name at the given position.

$ dotnet run
John Doe is a gardener
JD
J

Source

C# operators and expressions

In this article we have worked with the main kinds of expressions in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.