ZetCode

C# expression

last modified July 5, 2023

In this article we work with expressions in C#.

An expression is a unit of code that evaluates to a value.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands.

There are several types of expressions in C#:

Func<int, int> square = (int x) => x * x;

On the right side of the assignment, we have a function body expression. The expression results in a value.

Console.WriteLine("falcon");

In contrast, a statement such as writing to a console, does not result in a value.

C# lambda expression

A lambda expression is an anonymous function not bound to an identifier. The lambda declaration operator => to separate the lambda's parameter list from its body.

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

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

In the example, we filter out all positive values from an array of integers. The Array.FindAll function takes a predicate function as a second parameter. With (e) => e > 0 lambda expression we define this predicate.

$ dotnet run
1 3 4 2 1 3

C# query expression

A query expression allows us to extract and transform data in C# with queries.

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
    select val;

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

In the example, we use a query expression to find all even values in an array.

$ dotnet run
-2 4 6 2 0 -4 2 8

C# switch expression

The switch expression provides branching control that is based on the comparison of an expression with a set of patterns. Unlike classic switch keyword, it returns the value of the matching arm.

Program.cs
int age = 23;
string name = "Peter";

List<string> colors = new List<string> {"blue", "khaki", "orange"};
var nums = new int[] {1, 2, 3, 4, 5};

Console.WriteLine(check(age));
Console.WriteLine(check(name));
Console.WriteLine(check(colors));
Console.WriteLine(check(nums));

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

In the example, we find out the data type of a variable using switch expression.

$ dotnet run
integer
string
list of strings
array

C# with expression

The with expression produces a copy of its operand with the specified properties and fields modified.

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

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

record Point(int x, int y);

In the example, we create a copy of a point with its y member modified to 3.

$ dotnet run
Point { x = 0, y = 0 }
Point { x = 0, y = 3 }

C# interpolated string expressions

We can put expressions inside interpolated strings to create formatted strings. Interpolated strings are prefixed with the $ character.

Program.cs
int x = 5;
int y = 6;

Console.WriteLine($"{x} * {y} = {x * y}");

In the example, we create a string in which we multiply two values.

$ dotnet run
5 * 6 = 30

C# expression body definitions

Expression body definitions provide a concise definition for a function, constructor, property, indexer, or finalizer.

Program.cs
Func<int, int> square = (int x) => x * x;

int r = square(5);
Console.WriteLine(r);

var u = new User("John Doe", "gardener");
Console.WriteLine(u);

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

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

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

In the program, we have an expression body definition for the square function, User constructor, and ToString member function.

$ dotnet run
25
John Doe is a gardener

Source

Expressions - language reference

In this article we have worked with expressions in C#.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.