Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

when: practical reference

when: practical reference: when adds a filter to catch or a guard to a switch pattern.

Version: C# language; verified against C# 14 reference

Syntax

when /* grammar-specific form */

when adds a filter to catch or a guard to a switch pattern.

Use it to narrow a case without catching an exception that does not qualify.

A filter should be safe and side-effect free; false continues the search for a handler.

An exception thrown by an exception filter is treated as false.

The complete program actually uses when; its exact expected stdout is filtered.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

try { throw new ArgumentException("x"); } catch (ArgumentException error) when (error.Message.StartsWith("x")) { Console.WriteLine("filtered"); }

Result

filtered

The complete program actually uses `when`; its exact expected stdout is `filtered`.

Sources