Skip to content

Suppressions

Ian Wold edited this page Nov 10, 2026 · 3 revisions

Examples use the Pet union and IFlier interface from Home.

CS8509 on a switch expression is suppressed when every case is either handled by an arm or ruled out by earlier code, and at least one case needed the earlier code. For a tuple switch, the same applies to every combination of cases. CS8846 is handled the same way, and it can also count an arm whose when clause always holds for a case (see Arms that handle a case).

CS8655 and CS8847 are the same warnings for null alone: every case is handled, but the compiler's nullable flow state says the input could be null. They're suppressed when earlier code rules null out in a way the flow state doesn't follow, like shapes.Where(s => s is not null).Select(s => s switch { ... }) (see Null).

IDE0072 is suppressed on any switch expression over a union or closed hierarchy, complete or not: where a case is missing, CS8509 already says so, with Add missing arms as its fix. IDE0010 is suppressed on any switch statement that handles every case left after narrowing, whether or not narrowing was needed. The IDE doesn't understand unions at all.

The package only suppresses what it can prove. If any piece of the reasoning below doesn't apply, the warning stays.

What can be switched on

  • union declarations, generic or not, from source or from a referenced assembly.
  • Nullable unions, like Pet?. Null is then a case too (see Null).
  • Custom struct unions: a [Union] struct that implements IUnion.
  • Custom class unions that can't change once constructed. The class has to be sealed and derive directly from object. Its instance fields all have to be readonly, it can have no settable properties other than init, and it can have no field-like events. For a class from a referenced assembly, its fields are checked in metadata.
  • For a custom union declared in source (struct or class), its Value (and its HasValue and TryGetValue, if it has them, which patterns may call instead) has to read only the union's own instance fields and auto-properties, not what one of them refers to (_slot[0], _box.Value) or a static field: another reference to that storage could change it without the union changing.
  • Closed hierarchies: closed classes and records, including generic ones. A closed type nested inside another closed type is expanded to its own subtypes. this inside a closed type can be switched on too.
  • A union's case types are counted the way the compiler counts them. A case type that's a closed hierarchy is its leaf types, so with union Result(Ok, Error) and a closed Error, past if (r is Ok) return 0;, r switch { NotFound => 1, Timeout => 2 } is complete. A bool case type is true and false, and an enum case type is its members (plus the values no member has, unless CS8524 is turned off). Two enum case types' values don't mix, even where they're the same numbers.
  • A bool or an enum, narrowed the same way: if (c == Color.Red) return 0; leaves Color.Green and Color.Blue. For an enum, this only helps where CS8524 is turned off (by NoWarn or .editorconfig): otherwise the switch also has to handle values no member has, which only a discard does, and suppressing CS8509 would hide CS8524.
  • A tuple, like (a, b) switch, with at least one element of a type above. Its other elements can be anything: a bool or enum has its values as its cases, and any other type has a single case that only a pattern matching every value covers, like _ or int. There can be at most 4,096 combinations of cases. Each element is followed separately, and some guards rule out combinations (see Tuples). The tuple can be a literal, or a variable of a tuple type (var t = (a, b); ... t switch).
  • Any of these inside something that can be followed piece by piece: ((Pet)pet) switch, (flag ? a : b) switch and (maybe ?? fallback) switch (ruled out where every branch that doesn't throw rules it out), owner?.Pet switch (as owner.Pet, but it can be null), a call to a method of your own, new Owner(cat).Pet, or a LINQ element like pets.First(p => p is not Bird) (see What a value was assigned).
  • An object of any type whose arms look at unions inside it, like owner switch { { Pet: Cat } => 1, { Pet: Dog } => 2 } (see Nested patterns).

These are not reasoned about, so their warnings stay:

  • Class unions that could change: unsealed ones (a derived class could add state that Value reads), or ones with a mutable field, a settable property or a field-like event.
  • Custom unions whose Value reads through to other storage, as above.
  • Any other type, such as object, unless its arms look at a union inside it.
  • A tuple with no union or closed type in it, such as (flag, n).

Generic code

Generic code that a value comes from, or that a test is in, is read with the type arguments it's used with: a call's (Opt.Some(1) gives a Some<int>, and r.Map(f) on a Result<int, string> can give an Ok<int> or an Err<string>), a generic type's (Factory<int>.Make(1), Factory<int>.Empty), and a helper's (r.IsErr() with static bool IsErr<T, E>(this Result<T, E> r) => r is Err<E>; tests for an Err<string>). That goes for what a method returns, an out value, an initializer, what constructors set a member to, and a helper's body.

Where a type parameter is still unknown, a type made from it only rules out what no type argument could make it: Some<T> can't be a None, but could be a Some<int>, so in void M<T>(Option<T> o), past if (o is not Some<int>) return;, None is ruled out but Some<T> isn't. A pattern on a value of a type parameter says nothing about a union, though: generic code is compiled once and tests a union it's given boxed, which is never one of its cases, so static bool IsBird<T>(T value) => value is Bird; is always false for a Pet.

Which values are followed

  • Locals and by-value parameters. This includes foreach variables (plain, deconstructed and await foreach), and variables declared by the condition itself, which are tested after they're set: if (value is not Pet pet || pet is Bird) return;, if (!TryGet(out var pet) || pet is Bird) return;, if (map.TryGetValue(key, out var pet) && pet is not Bird) { ... }, value is Pet pet && pet is not Bird ? ... : ..., while (queue.TryDequeue(out var pet) && pet is not Bird) { ... }, and Next() is not Bird and var pet.

  • Primary constructor parameters of a class, as long as nothing ever assigns them.

  • Members that can't change once the object is constructed, and chains of them (household.Owner.Pet), starting from a followed local or parameter, from this in a class, or from a static member:

    • readonly fields, instance or static
    • get-only and init auto-properties
    • properties whose getter just returns field, with no setter other than init (for a partial property, going by the part that implements it)
    • positional properties of records and readonly record structs
    • properties whose getter just returns one of these from this (public Pet Pet => _pet;, get { return _pet; }), up to four getters deep
    • anonymous types' properties, including what a query's let makes
    • properties like these from referenced assemblies (checked in metadata)
    • a KeyValuePair's Key and Value, and a System.Tuple's Item1, Item2, ...
  • Fields of a struct, including a tuple's elements (by name or as Item1) and a record struct's positional properties, wherever the struct itself is followed: t.Item1, r.Pet for var r = GetPair();, box.Inner.Pet. They only change when the struct does, so writing any part of the struct (a field, a setter, a method that isn't readonly) counts as writing them.

  • Every element of an immutable collection (ImmutableArray, ImmutableList, ImmutableHashSet, ImmutableSortedSet, ImmutableQueue, ImmutableStack, FrozenSet) held in a followed local or parameter: past if (pets.Any(p => p is Bird)) return; or if (!pets.All(p => p is not Bird)) return;, no element is a Bird, in a foreach over it, a LINQ lambda over it, or an element taken from it (pets.First()).

  • A nullable union's value. maybe.Value on a Pet? is followed as maybe.

  • An ImmutableArray's elements, indexed by a constant or a followed variable: pets[0], pets[i] (as long as i doesn't change in between).

  • this in a class, for switching over a closed hierarchy.

  • Copies. After var local = pet; or other = pet;, what's known about pet carries over to the copy. This covers chains of up to six copies, copies of a member's owner (var same = owner; ... same.Pet), and copies made by:

    • var patterns: var other => ..., pet is var copy, case var other:
    • typed patterns that bind the same object: owner is Owner o, owner is { Pet: not Bird } o, shape is Polygon p (not a case taken out of a union, like pet is Cat c), and a guard's is not that binds it for the statements after: past if (owner is not Shelter shelter) return;, shelter is owner, so what's known about owner.Pet holds for shelter.Pet, and so does what's known about it when owner is a Shelter (if (owner is Shelter { Pet: Bird }) return 0;)
    • designations inside subpatterns, which bind the member they're on: { Pet: not Bird and var p } binds owner.Pet, (not Bird and var x, _) on a tuple literal binds its element, and Kitten { Toy: var toy } binds what the Kitten holds
    • deconstruction: var (x, n) = (pet, 1);, var (x, n) = owner; for a record (through its generated Deconstruct), (Pet x, int n) = t;, and a KeyValuePair or System.Tuple (through theirs)

    What was known when the copy was made always carries over. Facts established about the source later also carry over, as long as nothing has written it since the copy.

These are not followed (but see Following mutable state):

  • fields that aren't readonly, except a struct's
  • settable, virtual, abstract and override properties, except a struct's auto-properties, and computed properties that do anything but return a followed member
  • elements of arrays and other collections, except an ImmutableArray's (and what's known about every element of an immutable collection)
  • ref, in and out parameters, and ref locals
  • this in a struct, and primary constructor parameters of a struct (this = ... replaces them)
  • readonly members inside init accessors and member initializers, where they can still be assigned. Inside a constructor's own body, the members of what it's constructing (from this, or static ones in a static constructor) are followed, since only that body can assign them, and it does so visibly. That stops at a lambda (which could run after a later assignment), and if the constructor takes a reference to one of them.
  • readonly members inside a lambda that could be made while the object (or, for static members, the type) is still being constructed, which would carry facts from before the member is set for good: a lambda in an override (a base constructor could call it), or in a member the constructors, initializers or init accessors call, directly or through others. If construction hands this to other code (or a static constructor or initializer calls another type, which could call back), that goes for a lambda in any member, and for an object's readonly members read through any variable.

What a value was assigned

Where the analysis stops, going back, at the statement that last assigned the value, what it was assigned says which cases it can be in:

  • A union made from a case (Pet pet = new Cat("Tom");, pet = cat;, new Pet(cat)) is only that case. A closed type made from a derived type (Shape shape = new Circle();) is only that. A Pet? made from a Pet is what the Pet is, and has a value.
  • flag ? new Cat("Tom") : new Dog("Rex") is either, and a ?? b is what both sides are. A branch that throws gives no value: flag ? a : throw ... is what a is, and a ?? throw ... is a, and not null. A call to a method that never returns counts as a throw here: a [DoesNotReturn] method, or a throw helper like static T Fail<T>() => throw ...;.
  • A followed value (pet = other;) is whatever is ruled out for it there.
  • A call to a method declared in this compilation that can't be overridden is what all its returns are (static Pet MakeCat() => new Cat("Tom");), read with the call's type arguments (see Generic code). So is await on a call to an async method like that (await MakeCatAsync(), with or without .ConfigureAwait(false)).
  • A member of a new object is what it was set to: new Owner(cat) for a record's positional property, new Owner { Pet = cat }, owner with { Pet = cat } (and with leaves the rest as they were). Only as long as what the initializer does after that just stores values, in fields and auto-properties: a later setter or init accessor of the type's own (new Settings { Pet = cat, Level = 3 }, where Level's init sets Pet) could set it again. And for with, only when the record's copy constructor (and its base records') is the one the compiler generates: one written by hand can do anything.
  • A LINQ element that passed the chain's filters: First, Last, Single (with or without a predicate), ElementAt, MaxBy and MinBy, and List<T>.Find and Array.Find. The OrDefault forms and Find can also give a default union, which isn't a case the switch has to handle.
  • A switch expression is what every arm that doesn't throw gives, each read in its arm: pet = pet switch { Bird => new Cat("Tom"), var other => other }; leaves no Bird.
  • An out argument to a method declared in this compilation that can't be overridden is what every assignment the method makes to that parameter is: past TryCat(out var pet);, with pet = new Cat("Tom"); the method's only assignment, pet is a Cat.
  • A readonly field or get-only auto-property that nothing in its type assigns (not even a constructor) always holds its initializer's value: static readonly Pet Favourite = new Cat("Tom"); is a Cat wherever it's read.
  • A labeled statement that assigns it, as for the statement without the label, with what held on the way in taking the label into account: past retry: if (pet is Bird) { if (++tries > 3) return 0; pet = Next(); goto retry; }, pet is no Bird.
  • An if that assigns it in some branches: every branch that falls through has to rule the case out, and one that doesn't assign it gets what held before the if. So if (pet is Bird) pet = new Cat("Tom"); rules out Bird.
  • A switch statement that assigns it: what holds at every break out of it, and, without a default:, what held before it. So switch (kind) { case 0: pet = new Cat("Tom"); break; case 1: pet = new Dog("Rex"); break; default: return 0; } leaves a Cat or a Dog.
  • A try that assigns it: what holds at the end of the try block and of every catch that falls through, then the finally. A catch that doesn't assign it only knows what held before the try, and only if the try block doesn't assign it either, since it can start anywhere in the block. So try { pet = Load(); if (pet is Bird) return 0; } catch { return -1; } rules out Bird.
  • x ??= e: what it held before (and that it wasn't null), or what e is. Past if (shape is Square) return 0; shape ??= new Circle();, shape is no Square.
  • A condition that assigns it before testing it: past if ((pet = Next()) is Bird) return 0; or while ((pet = Next()) is Bird) { }, pet is no Bird, and in if ((pet = Next()) is not Bird) { ... } or while ((pet = Next()) is not Bird) { ... } it isn't one either. The assignment has to be the condition's only write to it, with nothing in the condition reading it before. A condition that writes it some other way (an out argument, a declaration) and then tests it, joined by && (or ||), gets what the tests after its last write say: in if (TryGet(out pet) && pet is not Bird) { ... }, pet is no Bird.
  • A local whose every write rules a case out never holds that case, anywhere, even in a loop that writes it: with Pet pet = new Cat("Tom"); and only pet = pet switch { Cat => new Dog("Rex"), _ => new Cat("Tom") }; after that, pet is never a Bird. Every write has to be its initializer or a plain assignment, and it's only for the local and members of it that can't change (not a settable property under Following mutable state).
  • A readonly field or get-only auto-property of a class that every constructor sets once, in a statement of its own body (or leaves to the one it calls with : this(...)), and that nothing else assigns: what every constructor sets it to. So with public Owner(Pet pet) { if (pet is Bird) throw ...; _pet = pet; } as the only constructor, _pet is never a Bird, in any member. (Not null, though: code a constructor calls before it sets the member reads the default. And not in a struct, which can be made without a constructor.)

Tests that rule a case out

Each row shows what's ruled out past if (<test>) return;. When the switch is inside the if, the opposite cases are ruled out.

Test Rules out
pet is Bird, pet is Bird b, pet is Bird { } Bird
pet is Bird or Dog, pet is Bird || pet is Dog Bird, Dog
pet is not Cat, !(pet is Cat) Dog, Bird
pet is not (Cat or Dog) Bird
pet is IFlier, an interface Bird implements Bird
pet is Bird && pet is IFlier, pet is IFlier and Bird Bird
flag || pet is Bird Bird
pet is Bird | pet is Dog, pet is not Bird & pet is not Dog (the logical operators that evaluate both sides) Bird, Dog
(pet is Bird) == true, isBird != false Bird
flag ? pet is Bird : pet is Bird or Dog, pet is Bird ? true : false Bird
shape as Circle != null, (shape as Circle) is not null, circle != null for var circle = shape as Circle;, pet.Value as Bird != null Circle (or Bird)
pet.Value is Bird, pet.Value is not (Cat or Dog), pet is { Value: Bird } as for pet itself
owner?.Pet is Bird, household?.Owner?.Pet is not (Cat or Dog) as for owner.Pet, wherever that's read (owner can't be null there)
pet is null, pet is Bird or null null (and Bird)
!maybe.HasValue, maybe == null, for a Pet? null
pet switch { Bird => true, _ => false } used as a condition Bird
(a, b) is (Bird, _) Bird for a
owner is { Pet: Bird }, owner is (Bird, _), household is { Owner.Pet: Bird } Bird for owner.Pet (or household.Owner.Pet)
pet.IsBird(), Flies(pet), pet.CanFly, animal.IsBird, pet.Is<Bird>(), r.IsErr(), !r.TryGetOk(out var value) whatever the helper's body rules out (see below)
shape.Kind == ShapeKind.Circle, shape.Kind is ShapeKind.Circle or ShapeKind.Square, shape is { Kind: ShapeKind.Circle }, for a discriminant Kind the types whose Kind that is (see below)
(pet is Bird) is true, isBird is not false Bird
u.TryGetValue(out Bird? b), !u.HasValue, on a custom union with the non-boxing access pattern Bird (or null)
n is int or long, for union Number(int, long, string) int, long
value is IComparable, for union IntOrCat(int, Cat) int
flag, !flag, flag == true, for a bool true (or false)
c == Color.Red, c is Color.Red, c > Color.Green, for an enum the members it holds for
s is true, t is Keyword.If, t is > Keyword.If, for a union with a bool or enum case type the values it holds for

A helper is a method, local function, property getter, extension method or C# 14 extension member declared in this compilation, that can't be overridden, isn't async, doesn't write the parameter the value is passed as, and whose body is a single bool expression (=> p is Bird), or a block it can be read through. A call to one reads as its body, with the argument in place of the parameter (or of this, for a union's own members), and the call's type arguments in place of the helper's type parameters and those of a generic type it's in (static bool Is<T>(this Pet p) => p.Value is T;, static bool IsErr<T, E>(this Result<T, E> r) => r is Err<E>;, a generic union's own bool IsPending => this is NotAsked or Loading;). Helpers can call helpers, up to three deep.

A block is read statement by statement: statements that don't return (declarations, calls, assignments), and ifs (with or without an else) whose branches are statements like those ending in a return or a throw. Past such an if, what its condition says holds. A case is then known true (or false) where every return it can reach returns something true (or false) for it. So a Try method reads as the test it makes:

public bool TryGetOk(out T value)   // in union Result<T, E>(Ok<T>, Err<E>)
{
    if (this is Ok<T> ok) { value = ok.Value; return true; }
    value = default!;
    return false;
}

if (!r.TryGetOk(out var value)) return 0; rules out Err<E>. A block with anything else in it (a loop, a switch, a try) isn't read.

A union member that isn't marked readonly still counts as not changing the union if its body (an expression or a block) assigns nothing of this or its fields, passes none of them by reference, declares no ref local, makes no lambda or local function, and calls no member of them that isn't readonly.

A discriminant is a property that each sealed type of a closed hierarchy overrides with a constant, as in TypeScript: public override ShapeKind Kind => ShapeKind.Circle; in Circle (or get { return ...; }), and so on. A test of the value's discriminant (==, !=, a pattern, a property pattern, a case label of switch (shape.Kind)) is true for the types whose constant passes it and false for the others. The constant has to be of an enum, bool, char, integer or string type, the property's own type as written, so that it compares exactly; floating point (NaN), decimal and object (boxed) properties aren't read. A type that isn't sealed (a subclass could override it again), whose getter does anything else, or a test that converts the property first (shape.Sides == 4.0) says nothing about that type.

A bool local stands for the condition it was set to, when the value it tests never changes in the function: set where it's declared (var isBird = pet is Bird;), or by its only assignment (bool isBird; ... isBird = pet is Bird;). So does a local set to x as T, in a null check.

A custom union's TryGetValue(out T value) and HasValue are what the compiler uses to match u is T and u is null when the union has them, so they're read as those tests.

A test on what the value is a member of (owner is { Pet: Bird }) rules out cases for the member wherever it's read, since what it's read from can't be null there.

These rule nothing out, or less than you might expect:

  • pet is Bird && flag (or pet is Bird & flag) rules nothing out on its own, because flag might be false. With pet is Bird && !flag too, together they rule out Bird: a case ruled out for every value of up to two bools that guards test is ruled out.

  • pet is Bird { Name: "Polly" } and (a, b) is (Bird, Cat) match only some Birds, so Bird isn't ruled out.

  • zoo is Parrot says nothing about Animal, even if Parrot derives from Animal.

  • n is long doesn't cover int, because a boxed int is not a long.

  • pet switch { Bird => true, Dog => flag, _ => false } rules out only what every arm agrees on.

  • A negated test (is not T) rules out a case only when no value of that case could ever be a T. That holds for a sealed class, struct or enum that isn't a T, or a type with no conversion to T at all. An unsealed class could have a subclass that is a T, and a type parameter could be anything:

    • thing is not IFlier doesn't rule out an unsealed Rock, but does rule out a sealed class SealedRock.
    • option is not None doesn't rule out T in union Option<T>(T, None).
  • A test against a union type itself isn't interpreted, unless that union is one of the case types (see Nested patterns).

  • Debug.Assert(pet is not Bird) rules nothing out, because it's compiled out of release builds.

Tuples

In a tuple switch, a test on one element rules cases out for that element, whatever the others are. So past if (a is Bird) return 0;, (a, b) switch { (Cat, _) => 1, (Dog, _) => 2 } is complete.

An if guard (or branch) that tests several elements together rules out the combinations it covers:

  • if (a is Bird && b is Bird) return 0; rules out (Bird, Bird).

  • if ((a, b) is (Bird, Bird) or (Cat, Cat)) return 0; rules out both of those combinations.

  • if (!(a is not Bird || b is not Bird)) return 0; rules out (Bird, Bird).

  • a is Bird && b is Bird ? 0 : (a, b) switch { ... }, and the right of || and &&, rule out what the left side does.

  • An earlier switch (a, b) { case (Bird, Bird): return 0; } that no section breaks out of, and that has no default:, rules out (Bird, Bird). In a section of a switch statement over (a, b) with a single label, that label matched, and the labels before it didn't.

Combinations aren't ruled out by a guard with an unrelated condition, such as a is Bird && b is Bird && flag. They're also forgotten as soon as anything writes any of the elements. Combination facts only come from the places above, in the same function, with no label in between.

Elements that aren't unions are followed too: past if (flag) return 0;, (pet, flag) switch { (_, false) => 1 } is complete.

Where the test can be

Before the switch, in the same block or an enclosing one:

  • if (test) <exit>, where the exit is one of:

    • return, throw, break, continue, yield break, or a goto past the switch
    • a call to a [DoesNotReturn] method
    • a call to a method that always throws: its body is => throw ..., or ends in throw with no return anywhere in it
    • a block that ends in any of these

    These calls don't count as exits: a [Conditional] method (it may be compiled out), a method that only sometimes throws, an async method (it returns a faulted task), and a virtual, abstract or interface method.

  • A call to a guard helper with a [DoesNotReturnIf] parameter: past Guard.IsTrue(pet is not Bird);, with [DoesNotReturnIf(false)] bool condition, Bird is ruled out. Not Debug.Assert, which is [Conditional].

  • A call to a helper of your own whose block throws for some cases (an assertion function, as TypeScript calls it): past Guard.NotBird(pet); with static void NotBird(Pet pet) { if (pet is Bird) throw new ArgumentException(); }, or var cat = RequireCat(pet); with one that throws unless pet is a Cat and returns it, what's ruled out at every way out of its body that returns is ruled out. The block is read as a helper's is.

  • if/else where only some branches fall through, including else if chains. A case is ruled out if every branch that falls through rules it out, so if (flag) { if (pet is Bird) return 0; } else { if (pet is Bird) throw ...; } rules out Bird.

  • Inside nested blocks, lock, using, checked, unchecked, unsafe and fixed.

  • Inside a try, if every catch exits too. A catch that falls through could run before the guard did.

  • A guard with a label on it, even one whose block writes the variable before jumping back to the label (see What a value was assigned).

  • A switch statement on the same value. If control falls out through a section's break, one of that section's labels matched. If there's no default:, falling out can also mean no label matched. So switch (pet) { case Bird: return 0; } rules out Bird. A switch statement on the value's discriminant (switch (shape.Kind)) works the same way.

  • A statement that's sure to throw for some cases: var n = pet switch { Bird => throw ..., Cat c => ..., Dog d => ... };, _ = pet is Bird ? throw ... : 0;, Console.WriteLine(pet is Cat or Dog ? "ok" : throw ...);, or x ?? throw ... (which rules out null). A call to a method that never returns ([DoesNotReturn], or a throw helper) counts as a throw: Bird => Fail<int>(). This doesn't count when the throwing part is only evaluated sometimes (the right side of &&, || or ??, a branch of ?:, inside a lambda), or when it's an argument to a [Conditional] call such as Debug.WriteLine.

  • A loop just before the switch. It ended either because its condition was false, or at a break, so what's ruled out is what holds both ways: after while (pet is Bird) pet = Next(); (or do/while, or for), the condition was false, even though the body writes pet; after while (true) { pet = Next(); if (pet is not Bird) break; }, what held at the break holds. A break from an inner loop or switch doesn't count, and a break with a finally on the way out that writes the variable holds nothing. The condition mustn't write the variable, except to assign it before testing it. If the loop writes the variable, nothing known from before the loop survives, except what every write to a local rules out (see What a value was assigned).

  • The assignment the value last got (see What a value was assigned).

  • Before a label that control gets to by falling in or through gotos from earlier on: what holds on every way in. if (pet is Cat) goto Known; if (pet is Bird) return 0; Known: ... rules out Bird. Where the statement before the label can't complete (return 0; Found: ...), control only gets there through its gotos, which is how C# breaks out of a loop to a label: foreach (var p in pets) { found = p; if (found is Bird) goto Found; } return 0; Found: return found switch { Bird b => ... };.

Around the switch:

  • The then or else branch of an if, either branch of ?:, or the right side of && or ||.
  • An arm of an outer switch expression over the same value. That arm's pattern matched, and the earlier arms didn't. An earlier arm with a when clause only rules out the cases its clause always holds for, like _ when pet is Dog. The arm's own when clause held, too, whatever the outer switch is over (n switch { > 0 when pet is not Bird => pet switch { ... }, ... }), and an earlier arm whose pattern matches anything, like _ when pet is Bird, didn't match because its clause didn't hold. A when clause on what the arm binds the input to (var p when p is Bird, or Shape s when s is Circle on a closed hierarchy) says the same about the input. The outer switch can also be on what the value is a member of, or on a tuple literal with the value (or what it's a member of) as an element: in (a, b) switch { (Bird, _) => 0, _ => a switch { ... } }, a isn't a Bird, and in (a, b) switch { (Bird, Bird) => 0, _ => (a, b) switch { ... } }, (Bird, Bird) is ruled out.
  • A section of an outer switch statement over the same value (or what it's a member of, or a tuple literal with it in). One of its labels matched, with its when clause holding, and the labels before it didn't. A default: section counts as coming after every label. None of this applies if the switch statement uses goto case or goto default.
  • A catch with a filter: catch (Exception) when (pet is not Bird) { ... }. Filters run before the finally blocks inside the try, so this only counts if nothing in the try block (or a filter) writes the variable.
  • The body of a while or for loop. The condition held when the iteration started, as long as nothing in the body writes the variable before the switch.
  • The body of a do loop. Only what holds both on the way into the loop and whenever the condition sends control back around is used.
  • The body of a foreach over a LINQ chain. See Facts across functions.
  • A loop that contains the switch. Facts from before the loop still hold, as long as nothing in the loop writes the variable. That includes writes after the switch in the body, and in a for loop's incrementer.

A switch statement's own sections can assign the variable it switches on (switch (state) { case Idle: state = new Running(); break; ... }): they only run once it has matched, so for IDE0010, what held on the way in still holds. A loop or goto around it is still a write before the next time round.

It works the same way in iterators, async methods, lambdas, local functions and top-level statements.

Facts across functions

  • Lambdas and query clauses. A test outside a lambda or query carries into it if the variable never changes. That means nothing assigns it after it's declared, and its declaration can't run again (a goto that jumps back over it would re-run it). foreach variables and unassigned parameters qualify. It also carries in, as in TypeScript 5.4, when every write is done by the time the lambda is made: every write is in a statement that ends before the lambda, no loop around the lambda has a write in it, the function has no goto, and everything between the lambda and the variable's own function is a lambda or query (a local function could be called before the writes). So if (reset) pet = new Cat("Tom"); if (pet is Bird) return () => 0; return () => pet switch { Cat => 1, Dog => 2 }; is complete.

  • Local functions. A captured variable gets what holds for it at every call to the local function, when every reference to it is a direct call from outside its own body, and it runs when it's called (it isn't async or an iterator, unless the variable never changes). A test inside a local function works as usual.

  • LINQ. A lambda that receives each element of a LINQ chain (Enumerable, ParallelEnumerable, or the ImmutableArray extensions) gets what that chain's filters established: pets.Where(p => p is not Bird).Select(p => p switch { Cat => 1, Dog => 2 }). The same applies to query syntax (from p in pets where p is not Bird select ..., with let, a second from, and group ... into), to foreach (var p in pets.Where(...)), and to the elements a chain hands back (see What a value was assigned).

    • The filters are Where (with or without the index), TakeWhile, and List<T>.FindAll and Array.FindAll. A filter's predicate has to be a lambda with a single expression, or a method group for a helper (see Tests that rule a case out). SkipWhile(p).First() is an element p was false for.
    • The filter is followed back through operators that pass elements on unchanged: Where, OrderBy, OrderByDescending, ThenBy, ThenByDescending, Order, OrderDescending, Reverse, Take, Skip, TakeLast, SkipLast, TakeWhile, SkipWhile, Distinct, DistinctBy, Except, ExceptBy, Intersect, IntersectBy, AsEnumerable, ToList, ToArray, ToHashSet, the parallel ones (AsParallel, AsSequential, AsOrdered, WithDegreeOfParallelism, ...), and Cast or OfType to the type the elements already are. It's also followed through a Select that picks the element or a member of it (Select(o => o.Pet), Select(p => (p, 1)), Select(p => new { Pet = p })), and through a local that never changes, set to a lazy query or to an immutable collection made from one (ToImmutableArray(), ToImmutableList(), ToImmutableHashSet(), ToImmutableSortedSet(), ToFrozenSet()), but not to a list or array, which could be changed later. Concat, Union and UnionBy keep what both sequences' chains rule out.
    • The receiving lambda can be a predicate, selector, keySelector, elementSelector, collectionSelector, outerKeySelector or innerKeySelector; either parameter of Zip's and Join's result selector, the element of SelectMany's (and the second parameter, when the collection selector doesn't depend on the element or is a group from GroupBy); the element in Aggregate with a seed; and List<T>.ForEach, Exists, TrueForAll and ConvertAll, and Array.ForEach.
    • Grouping and flattening back out hands back the same elements: GroupBy by a key alone, or Chunk, followed by SelectMany(g => g).
    • Operators that produce new elements (Select with anything else) or add elements (Prepend, Append, DefaultIfEmpty) cut the chain, and so does SkipWhile as a filter (except for the first element after it).
  • Local functions, private methods and constructors, and methods and constructors nothing outside the assembly can see. A parameter gets what holds for its argument at every call, but only when:

    • every reference to the function is a direct call: never converted to a delegate, never made from inside the function itself, and never a dynamic call by its name. A constructor's calls are new (or new(...)), : this(...), : base(...) and a primary constructor's base call; a record's copy constructor (which with calls), an attribute's constructor and an interpolated string handler's (which interpolated strings call) don't count. Nor does a constructor of a type named in a typeof or as a generic method's type argument (Activator.CreateInstance<Kennel>(), services.AddTransient<Kennel>()), which reflection could call with anything.
    • the compiler doesn't call it by pattern, without its name in the source: a method named Add (collection initializers), AppendLiteral or AppendFormatted (interpolated string handlers), Deconstruct, GetEnumerator, MoveNext, Dispose, DisposeAsync, GetAwaiter, GetResult, OnCompleted, Select, SelectMany, Where, Join, GroupJoin, OrderBy, ThenBy (and their Descending forms), GroupBy, Cast (query clauses), Slice, GetPinnableReference or TryGetValue, doesn't count
    • no [UnsafeAccessor] in the compilation names a method of its name
    • every call passes something whose case can be worked out: a value that can be followed, a new case, a call to a method of your own, and so on (see What a value was assigned)
    • for a method, it isn't virtual, abstract, override, extern or partial, doesn't implement an interface member (for its own type, or, being public, for a type that derives from its type), and isn't the entry point
    • for a private method, the calls are found in every part of its type, in any file
    • for an internal method (or one in an internal type), they're found in every file, and the assembly has no InternalsVisibleTo; a method other assemblies can see could be called from anywhere

    A generic method's parameter gets what its callers pass, as far as that goes without knowing its type arguments: a Some<int> passed for an Option<T> is a Some<T>, so it isn't a None. Null counts as ruled out at a call where the compiler's flow state says the argument isn't null. A class's primary constructor parameter that nothing assigns gets what its constructor was called with in every member: with internal class Owner(Pet pet) made only by new Owner(pet) past if (pet is Bird) return;, pet switch { Cat => 4, Dog => 4 } in its members is complete.

  • Deconstructed foreach. foreach (var (pet, n) in items.Where(x => x.Pet is not Bird)) gets what the chain's filters say about the element's member that pet is (a tuple element, or a record property read through its generated Deconstruct).

  • Lambdas called directly. A lambda's parameter gets what holds for the argument at every call, when the lambda is in a local that never changes and is only ever invoked (Func<Pet, int> f = p => ...; f(pet)), or when it's passed to a method of your own that only ever invokes it with one of its own by-value parameters, which it never assigns (Run(pet, p => ...) with R Run<T, R>(T value, Func<T, R> f) => f(value)). A lambda passed to a method from elsewhere gets nothing, since that method could call it with anything.

Arms that handle a case

An arm handles a case only if it matches every value of that case:

  • Cat, Cat c, Cat { }, Cat or Dog, _ and var x.
  • Subpatterns that match anything: Cat { Name: _ }, Dog(var name), Cat(_) and { Name: var name }, Dog { Name: _ or null }. Positional subpatterns count only through a Deconstruct method or a tuple.
  • Tuple patterns like (Cat, _) and (Cat, Dog) or (Dog, Cat), element by element.
  • Patterns that look inside, combination by combination (see Nested patterns).
  • For CS8846 only, an arm whose when clause always holds for a case, when nothing has written the value since the switch read it. For example, _ when pet is Dog => ... handles Dog, and so does var p when p is Dog => ....
  • For CS8846 only, arms whose when clauses between them hold for a case whatever up to two bool locals or parameters they test are: Cat when loud => 1, Cat when !loud => 2 handles Cat, as long as no clause writes loud.

These don't handle their case:

  • Cat { Name: "Tom" }
  • Dog { Name.Length: _ }, which also needs Name to be non-null
  • Dog { Name: { } }
  • Cat c when c.Name == "Tom"
  • a null arm on its own

Null

  • If nullable warnings are enabled and some case type can be null, null is a case too. This applies to case types like Cat?, an unconstrained T, or string? in Option<string?>. A null => arm has to handle it, or a test like is null or is Dog or null has to rule it out. Without this rule, suppressing CS8509 would hide CS8655, which the compiler only reports once CS8509 is gone.
  • Under #nullable disable, null doesn't need to be handled.
  • For a custom union, whether a case can be null comes from its single-parameter constructors. A Cat? cat parameter makes Cat a case that can be null.
  • For a nullable union (Pet?), a class union, or a closed hierarchy, the variable itself can be null, and nullable flow state decides. A Pet? that may be null needs a null => arm or an is null test, and one that's been checked doesn't. On a Pet?, is null covers both "no value" and a default union inside.
  • When only null is missing, the compiler reports CS8655 (or CS8847) instead of CS8509, and that's suppressed when earlier code rules null out where the flow state can't see it: a Where(s => s is not null) filter, a copy made before the null check, or a helper whose every caller passes a value that isn't null.
  • On a Pet?, { Value: P } is a pattern on the union inside (the union's own Value), which only matches where there is one: maybe is { Value: null } matches a Pet? holding a default union, not one with no value, so it doesn't rule null out.
  • A member a nested pattern looks at can be null as its declared type says (see Nested patterns): a closed-hierarchy member declared without ? needs no null, as the compiler goes by.
  • The compiler can report CS8655 on a struct union whose cases can't be null, after a loop that assigns it, going by its flow state through the loop. That isn't suppressed: which value it means can't be told.

What stops the narrowing

These between the test and the switch:

  • assigning the variable, including in a nested statement, earlier in the same statement as the switch, or in a deconstruction
  • passing it as ref or out, even to a scoped ref parameter
  • calling a member of the union that isn't readonly, since it could reassign this (unless its body only reads this, see Tests that rule a case out)
  • for a member of a struct variable, anything that runs a member of the variable that could write it: a setter through ++, --, a compound assignment or a deconstruction ((s.Count, var n) = ...), a Deconstruct, property getter, Length or indexer that a pattern on the variable calls (s is (1, 1), s is { Count: 5 }), or a method of an outer struct that calls one on its field
  • calling a this ref extension method (scoped or not) or a ref extension block member
  • for a custom struct union, setting its Value
  • a when clause that writes the variable
  • a label that a goto could jump to, unless every goto to it comes from earlier on (then what holds at each goto counts too), or from later on, with nothing from the label on writing the variable. A goto that leaves a try with a finally on the way stops it, since the finally could write the variable.
  • running in a finally block after the guard's return

These anywhere in the function, which stop the variable from being followed at all:

  • a lambda or local function that writes it
  • taking a reference to it: a ref local, new Span<Pet>(ref pet), &pet, __makeref(pet), a ref argument to a parameter that isn't scoped, an [UnscopedRef] member that returns ref this, a ref extension property that hands out a span, or a ref, in or ref readonly argument (even to a scoped parameter) to a method that hands back a reference or a ref struct, which could be to it: Unsafe.AsRef(in pet), MemoryMarshal.CreateSpan(ref pet, 1)
  • for a lambda or query that switches on a captured variable, any assignment to that variable that isn't done by the time the lambda is made (see Facts across functions)

These are fine and don't stop the narrowing:

  • reading the variable, passing it by value or in (except as above), and calling readonly members on it
  • assigning it, passing it as out, or passing it to a scoped ref parameter before the test
  • capturing it in a lambda that only reads it
  • assigning the switch's own result back: pet = pet switch { ... }, (pet, n) = (pet switch { ... }, 1), items[i] = pet switch { ... } (but not from inside a lambda in the right side, which could run after the assignment)
  • for a switch statement, its own sections assigning it
  • statements that don't write it, such as declarations, using, lock, checked, try, other loops and switches, await, and local functions

Nested patterns

Arms can look inside the input, and earlier code can rule out what's in there:

  • At the union a case holds, for a union whose case is a union. With union Thing(Pet, Rock), past if (t is Rock) return 0; if (t is Pet and Bird) return 1;, t switch { Pet and (Cat or Dog) => 2 } is complete.

  • At a member of a case that's a union or of a closed type, of a union or a closed hierarchy. With record Kitten(Toy Toy), past if (y is Kitten { Toy: Ball }) return 0;, y switch { Kitten { Toy: Mouse } => 1, Dog => 2 } is complete. Positional patterns work too: Kitten(Mouse). With a closed Expr and record Bin(Expr Left, Expr Right) : Expr, past if (e is Bin { Left: Lit }) return 0;, e switch { Bin { Left: Var or Bin } => 1, Lit => 2, Var => 3 } is complete, and so is r switch { Err<DomainError> { Error: Invalid } => 1, Err<DomainError> { Error: Missing } => 2, ... } over every leaf of a closed DomainError.

  • At a member of the object switched on that's a union or of a closed type, whatever its type. Past if (owner.Pet is Bird) return 0;, owner switch { { Pet: Cat } => 1, { Pet: Dog } => 2 } is complete, if owner can't be null.

  • In a tuple switch, element by element: (t, flag) switch { (Pet and (Cat or Dog), _) => 2 }, or (a, b) switch { ({ Pet: Cat or Dog }, { Pet: Cat or Dog }) => 1 } past guards on both Pets.

Each place the arms look at becomes another element, with its own cases, like a tuple's: one under a case is only there when the input holds that case. A place can be null as its member's declared type says. Every combination has to be one an arm without a when clause is sure to match, or include a case earlier code ruled out for its element, or be one earlier code ruled out across several places at once: past if (b is { Left: Lit, Right: Lit }) return 0;, b switch { { Left: Var or Bin } => 1, { Right: Var or Bin } => 2 } is complete. There can be at most six places, four steps deep, and 4,096 combinations.

Guards on a member add up even when the arms don't look inside: once earlier code has ruled out every case of a member that's a union or of a closed type, it has ruled out the case the member is in. Past if (r is Err<DomainError> { Error: Invalid }) return 0;, ... { Error: Missing } ... and ... { Error: Forbidden } ..., with those three the leaves of DomainError, r switch { Ok<int> ok => ok.Value } is complete.

Following mutable state

With unionnarrowing.follow_mutable_state = true in .editorconfig, these are followed too:

  • fields that aren't readonly, instance or static, and settable auto-properties
  • this in a struct, including a union's own members: union Pet(...) { int Legs() { if (this is Bird) return 2; return this switch { ... }; } }
  • array elements, indexed by a followed variable: pets[i]
  • in, ref and ref readonly parameters, and ref locals

Another thread could write any of these at any time, and so could code the method calls, through another reference to the same object or storage. So they're only followed when nothing comes between the test and the switch that could run other code: no calls (including property getters other than auto-properties', indexers, implicit ^ indexes and ranges, and function pointer calls), no object creations (new T() included), user-defined operators or conversions, string interpolation, await, yield, foreach or using, and nothing that takes a reference. Nor anything that runs code of the program's own without a call in sight: a Deconstruct written by hand (deconstructing, or a positional pattern), a list pattern's Length or Count and indexer (except on an array or a string), a collection expression's builder or Add and a spread's enumerator, a record's own copy constructor (with), == on a tuple with an element of a type that isn't built in, string concatenation with one (which calls its ToString), and the first use of a static member of another type that has a static constructor or static initializers. Assigning a member the value is read through (on any object), any array element, or this also stops it. And the value isn't followed from one function into another: not into lambdas, not from what a function's callers pass it, and not through a LINQ chain's filters (Where, First(predicate), a foreach over a filtered chain). What runs after the switch reads the value, like an arm's call, doesn't matter, unless a loop can bring control back around.

What it trusts

Like the compiler's own exhaustiveness check, the package assumes that a union's Value only changes when the union itself is written. That holds for union declarations. It also holds for custom struct unions and immutable class unions, unless their Value reads through to some other, shared state. For a custom union with TryGetValue and HasValue members, it assumes, as the compiler does when it matches patterns with them, that they agree with Value.

It also assumes that objects are made by their constructors (it doesn't follow code that reflection runs, beyond not giving a constructor what its callers pass when its type is named in a typeof or a generic method's type argument), and that immutable collections (an ImmutableArray included) aren't changed through the array they were made over, as with ImmutableCollectionsMarshal.

It assumes that Equals keeps its contract of never being true for null: a record's x as Circle != null is read as x is Circle only where the record's == and the Equals it calls (its own and its base records') are the generated ones, and a record further down that writes its own Equals(Circle?) is trusted to keep that contract too.