Repository navigation
Analyzers
Examples use the Pet union from Home. All of these analyzers work on struct unions. UN0002, UN0004 and UN0016 also work on closed hierarchies.
A warning, since what it reports is a case the switch is missing, which CS8509 would otherwise say.
Reported on a switch over a union or closed hierarchy when its default can only end by throwing, and that default catches cases the switch doesn't otherwise handle. That's a switch expression ending in _ => throw ... (or var x => throw ...), or a switch statement whose default: section can only end in a throw. A default counts as throwing when it calls a method that never returns (_ => AssertNever(pet.Value) with a [DoesNotReturn] method, a throw helper like static T Fail<T>() => throw ...;, default: return AssertNever(pet);), and when it does something else first and then throws (default: logger.LogError(...); throw new ...;). Debug.Fail doesn't count, since it's [Conditional]. The message names the cases. For a tuple switch, it names the combinations, the way Add missing arms would write them, with combinations that differ in one element put together: (Dog or Bird, _). An enum's values that no member has are written not (Color.Red or Color.Green).
The same goes for a throw statement right after a switch statement with no default: (and no section that breaks out of it), or right after two or more if (test) <exit> statements: it's a default in all but name. That's a common way to satisfy definite return (CS0161), so it's only reported when some case actually reaches it.
- An arm with a
whenclause doesn't count as handling its case. - Not reported when every case is handled, or ruled out by earlier code. A throwing
default:that's only there for definite return (CS0161) is fine. (UN0016, which is off by default, reports a throwing discard arm on a switch expression like that.) - Not reported when the default can end some other way, like returning a value.
- Not reported when the arms (or tests) cover everything inside the cases they look into (see Nested patterns):
Kitten { Toy: Ball }andKitten { Toy: Mouse }coverKitten. (UN0016 reports a throwing discard arm on a switch expression like that.)
It's also reported on an if/else if chain of at least two tests on one union or closed hierarchy value that ends in an else that only throws, when some case isn't sure to be caught by one of the tests: if (pet is Cat) ... else if (pet is Dog) ... else throw ... catches Bird. Every condition has to be a test of that one value. A test through a helper counts (if (IsCatOrDog(pet)) ..., read as its body, see Tests that rule a case out), but a chain that also tests something else (else if (flag), else if (other is Dog)) is more likely a list of preconditions, so it isn't reported. Neither is a single if with a throwing else. The same goes for ifs followed by a throw.
Reported on any of these, for a struct union with no case type that can be null:
-
default,default(Pet),new Pet(), and a parameter default likePet pet = default -
Activator.CreateInstance<Pet>(),Activator.CreateInstance(typeof(Pet))andRuntimeHelpers.GetUninitializedObject(typeof(Pet))
Not reported:
- when a case type can be null, because then the default is just that null
- for
defaultassigned to anoutparameter, which is how a Try method says "nothing here" - for
default!and(default)!, where the null-forgiving operator says it's meant (like= null!for a reference) - for a default that's only tested: by a type test or pattern, or a switch with an arm that matches it (
null, a discard,var), or a switch statement - for a local's initial value that nothing reads, because every way through the rest of the block assigns the local first:
Pet chosen = default; if (flag) chosen = a; else chosen = b; - for a custom union that declares its own parameterless constructor
- for
Activator.CreateInstancewith constructor arguments - for other structs (but see UN0018)
Reported on a switch arm or case label when earlier code ruled out every case it could match. It's tagged as unnecessary, so the IDE fades it. For a tuple switch, it's reported when every combination of cases the arm could match was ruled out or matched by an earlier arm: past if (a is Bird) return 0;, (Bird, _) => can't match. Arms that look inside count too (see Nested patterns): past if (y is Kitten { Toy: Ball }) return 0;, Kitten { Toy: Ball } => can't match.
It's also reported on a type test that can't be true: past if (pet is Bird) return 0;, pet is Bird b is always false, and past if (a is Bird) return false;, so is (a, b) is (Bird, _). There's no fix for this one, since removing a test changes what the code does.
The message names what earlier code ruled out: the cases, or the arm's pattern for a tuple or nested arm ((Bird, _), written without any comments in it), or "every case that's left" for an arm that matches anything.
Not reported:
- when the arm could still match some case, like
Dog or Birdafter ruling out onlyBird - when the arm could match null, like
null =>, which matches adefault(Pet) - on constant case labels, which a
goto casemight target - on an arm that's dead because of earlier arms, which the compiler already reports (CS8510, CS8120)
- on a switch expression's throwing arm that matches anything (
_ => throw ...), which UN0016 reports instead - when only a method's callers rule the cases out: here, a parameter of a method or constructor gets nothing from what its callers pass (unlike for the suppressions), so a guard that today's callers happen to make dead isn't faded. A local function's and a lambda's parameters still get what their calls pass.
- on a test in an argument to a
[Conditional]method, likeDebug.Assert(pet is not Bird): an assertion is meant to be one that can't fail - when the analysis can't follow the value
Reported on pet.Value switch { ... } and switch (pet.Value) for a struct union, when every pattern means the same thing on the union as on its Value. Patterns on a union test its Value, so switching on the union matches the same way, and the compiler then checks exhaustiveness. Type, declaration and null patterns qualify, as do discards, typed property patterns, not, and and or. In a switch statement, constant and default: labels qualify too.
It's also reported on a test like pet.Value is Cat c, which could be pet is Cat c, where the compiler checks that Cat is one of the cases.
Not reported:
- when a pattern means something else on the union:
var xbinds the union itself, and an untyped{ }is always true for the union - when a pattern isn't allowed on the union, like
stringor5forPet - when a switch statement has other kinds of labels, such as relational ones
- on class unions, because
.Valuethrows on null where a switch on the union doesn't - on
Valueproperties of anything other than a union, such asint?.Value
Reported when an array of a struct union is created full of default unions, or has elements reset to them:
-
new Pet[n], multidimensional arrays included -
GC.AllocateArray<Pet>,GC.AllocateUninitializedArray<Pet>andArray.CreateInstance(typeof(Pet), n) -
Array.ResizeandCollectionsMarshal.SetCount, which fill new elements with defaults -
Array.ClearandSpan<T>.Clear(), which reset elements -
ArrayPool<Pet>.Rent, which can return default elements
Not reported:
- for
new Pet[0] - for arrays with an initializer, or created from a collection expression
- for an array put in a local and filled right after, by
Array.Fill(array, value),array.AsSpan().Fill(value),new Span<Pet>(array).Fill(value), or afor (var i = 0; i < array.Length; i++)loop whose body starts witharray[i] = ...; - for unions with a case type that can be null
Reported on a field or auto-property (including one that uses field) of a struct union type, or of a struct with a union inside (up to four levels down), in a class, when it has no initializer and some constructor can leave it unassigned: on some way through the constructor that gets to its end (a way that throws doesn't), it isn't assigned. Much as CS8618 is for a reference that isn't nullable, this covers settable and init members as well as readonly ones. It's also reported when there's no constructor to assign it at all: an implicit or primary constructor, or no static constructor for a static member. For a member of a struct type, the message says where the union is: '_line' isn't assigned by every constructor, so it can be left as default(LineItem), with default(OrderState) in LineItem.State, ....
These count as assigning it:
- direct assignment
- tuple deconstruction
-
outorrefarguments - calling another constructor with
: this(...), which assigns what that one does - calling a
[MemberNotNull]method onthisthat names it, as for CS8618 - an initializer of
default!, which says it's meant (UN0003 doesn't report that either)
A required member is left to whoever creates the object, except that a constructor marked [SetsRequiredMembers] (including a primary constructor with [method: SetsRequiredMembers]) says it sets it, so it's reported when such a constructor doesn't.
Not reported:
- for a record's generated copy constructor, which copies every member from an object that was made by another constructor
- on members of structs
- on unions with a case type that can be null
A partial property is reported once: at its explicit backing field, if it has one, or else at its defining declaration.
Reported on calls that can return a default struct union:
-
FirstOrDefault,LastOrDefaultandSingleOrDefaultwithout adefaultValue, onEnumerableorQueryable ElementAtOrDefault-
DefaultIfEmpty()without adefaultValue -
GetValueOrDefault(key)on dictionaries, andNullable<Pet>.GetValueOrDefault() - your own generic methods, declared in source, that return
defaultordefault(T)for their type parameter on some path, when called with a union type argument (Helpers.Fallback<Pet>(),new Box<Pet>().Get()) -
new Lazy<Pet>()without a factory or value, whoseValueis made with the parameterless constructor - generic methods and properties from anywhere that say they can give the default, with a
T?return for an unconstrainedT, or[MaybeNull]:List<T>.Find,Array.Find,FirstOrDefaulton anImmutableArray,JsonSerializer.Deserialize<T>,AsyncLocal<T>.Value,CollectionsMarshal.GetValueRefOrAddDefault, and any library'sT? Get<T>() - a Try method's
outvalue, with[MaybeNullWhen(false)], when it's used anyway: the call's result is ignored (map.TryGetValue(key, out var pet);), or the variable is read where the call failed (if (!map.TryGetValue(key, out var pet)) { ... pet ... }) before anything assigns it. A fallback assigned in that branch (if (!queue.TryDequeue(out var pet)) pet = new Cat("Tom");) isn't reported, whether the variable was declared there or earlier. - your own generic methods that store
defaultthrough areforoutparameter, or into an array's elements (static void Reset<T>(ref T x) => x = default!;), when called with a union
Not reported:
- for overloads that take a fallback value
- for a result that's only tested, like
pets.FirstOrDefault() is Cat c - for LINQ's
Max,Min,MaxByandMinBy, which are annotatedT?for a sequence of a class, but throw on an empty one of a struct - for unions with a case type that can be null
- for generic methods whose
defaultcomes only from a lambda or local function inside them - for methods from other assemblies that don't say so: a plain
T Get<T>()can't be seen into
A union is a struct. Boxing it (to object, ValueType, an interface, or a generic T) boxes the union itself, not what it holds, so a boxed Pet is a Pet at run time. Reported on:
- a type test against something the box can't be:
(object)pet is Catand(object)pet is Cat or Dogare never true - a cast to one:
(Cat)(object)petalways throws, and(object)pet as Catis always null - an arm or case label testing for one in a switch on a boxed union:
((object)pet) switch { Cat => ... } -
ReferenceEqualswith a union, which is boxed afresh for the call, so it's never true -
pet.Equals(cat),object.Equals(pet, cat)andEqualityComparer<object>.Default.Equals(pet, cat), with a value of a case: never true, since a union only equals another of the same union -
pet.GetType() == typeof(Cat): never true (and!=always true)
The message says what's wrong, like '(object)pet is Cat' is never true: a boxed Pet is a Pet, not what it holds. Test the union itself, without boxing it. OfType<Cat>() and Cast<Cat>() on a sequence of unions are covered by CA2021. A boxed union in a variable of type object, or a generic T, isn't followed.
A union doesn't override ToString unless it declares its own, so formatting one gives its type name (Pet), not what it holds. Reported on pet.ToString(), $"{pet}", "..." + pet, and a union passed to Console.Write or WriteLine, a TextWriter's Write or WriteLine, StringBuilder.Append, AppendLine, Insert or AppendFormat, string.Format, Concat or Join, Convert.ToString, Debug or Trace output (Trace.TraceInformation, TraceWarning and TraceError included), and a logger's Log, LogInformation, LogWarning and the rest, and BeginScope (Microsoft.Extensions.Logging). It's also reported on a sequence of unions passed to string.Join, string.Concat or StringBuilder.AppendJoin, each of which gets formatted the same way.
An interpolated string passed to an interpolated string handler is formatted the same way, by the handler's AppendFormatted<T> (or one taking object): sb.Append($"{pet}"), Debug.Assert(ok, $"{pet}"), string.Create(provider, $"{pet}"), and a logging library's own handler. A handler with an AppendFormatted(Pet) of its own isn't reported.
A nullable union (Pet? maybe) is reported too, since its ToString is the union's: the message suggests maybe?.Value.
Not reported for a union that declares its own ToString. For a union declared in source, the message ends with "or override ToString in Pet", which fixes every place at once (see Override ToString).
Reported at Info. Reported on a switch expression's throwing discard arm (_ => throw ...) when every case (or, for a tuple switch, every combination) is handled already, or ruled out by earlier code, including where the arms cover a case by looking inside it. All the arm does then is catch a case added to the type later, at run time, instead of the compiler reporting the switch as not exhaustive. Not reported when the arm also catches a null the compiler would otherwise want handled. Without the arm, a default union throws SwitchExpressionException instead of the arm's exception.
Reported on the default of a struct or tuple that holds a union (as a field, an auto-property, or a tuple element, up to four levels down) whose default holds no case: default(Box), new Entry() for a struct without its own parameterless constructor, new Box[n], default((Pet, int)), and calls that can fall back to the default of one, like entries.FirstOrDefault(). The message says where the union is: Box.Pet. Structs from other assemblies aren't looked into, since their private fields aren't visible.
Not reported for new Box { Pet = pet }, or default(Box) with { Pet = pet }, where the object initializer (or with) sets every member with a union inside, nested initializers (new Outer { Inner = { Pet = pet } }) included; for default(Box)!; or for a ref field, whose default is a null reference, not a default union.
Reported on a public member of a union type (or a nullable union) in a record that doesn't declare its own PrintMembers or ToString, when the union doesn't declare its own ToString. The record's generated ToString prints each public member with its own ToString, so record Owner(Pet Pet) prints Owner { Pet = Pet }. Declare PrintMembers to print the member's Value, or, for a union declared in source, override ToString in the union, which fixes every record that holds one at once (see Override ToString).
Offered on a switch expression over a union or closed hierarchy (or a tuple with one in it). For CS8655 and CS8847, that's the null arm. Where the arms look inside the input (see Nested patterns), the missing arms are written the same way: Kitten { Toy: Ball }, Pet and Bird, { Pet: Dog }. Past 16 of those, it adds an arm for each case of the input they're in instead (Kitten => ...), so the switch ends up complete. It adds a Case => throw new NotImplementedException() arm for each case that no arm without a when clause handles and that earlier code doesn't rule out. It also adds a null arm where null matters (see Null). For closed hierarchies, it adds the leaf types. For a tuple, it adds an arm for each set of missing combinations that differ in one element, with that element's cases put together ((Dog or Bird, _)), or the whole case type, or _ where every case is missing with the same rest. An enum's values that no member has are written not (Color.Red or Color.Green).
Case types are written as patterns that mean them: a tuple case type as ValueTuple<int, string> ((int, string) would be a positional pattern), a nullable value type case as the type inside (char for char?, since the union holds a boxed char), and a type a member hides (a public Error Error { get; } in scope) as global::Error or Models.Error, whichever is shortest and still means it.
New arms follow the switch's existing layout: inline or one per line, with or without a trailing comma, with the existing arms' indentation and line endings. Comments stay where they are. It isn't offered when some arms are in an inactive #if section, where what it adds would clash with them in the other configuration, or for other types. Fix All adds a using once.
The same, for a switch statement: a case Dog: throw new NotImplementedException(); section for each missing case, before the default: section if there is one, with case types written as for Add missing arms. It's offered alongside the IDE's own fix, which adds a throwing default.
For a switch expression, replaces the throwing discard arm's pattern with the cases it catches: _ => throw ... becomes Dog or Bird => throw ... (or (Dog or Bird, _) => throw ... for a tuple), and var x => throw ... becomes (Dog or Bird) and var x => throw .... Where the arms look inside the cases, it names what's caught the same way: Kitten { Toy: Mouse } => throw .... A case added later is then missing, and the compiler reports it. For a switch statement, adds case Dog: and case Bird: labels to the default section, which keeps its default: for definite return; UN0002 then reports a case added later. For a throw after a switch statement, adds a section for the cases that throws the same way; after ifs, one more if (pet is Dog or Bird) throw ...; before it. For an if/else if chain that ends in a throwing else, adds one more else if (pet is Dog or Bird) before the else, that throws the same way (with nested patterns too, where every test in the chain is an is pattern). The else then only catches a case added later, which UN0002 reports.
A switch statement that handles every case of a union (or every case left after narrowing) still lets control fall out of its end, as far as the compiler can tell, since a default union matches no case. At the end of a method (or local function, or accessor) that's "not all code paths return a value" (CS0161, or CS1643 in a lambda), and after one that assigns a variable in every section, "use of unassigned local variable" (CS0165). Both are errors, so nothing can suppress them. This adds default: throw new UnreachableException(); to the switch (or InvalidOperationException where UnreachableException isn't available), and using System.Diagnostics; if the file doesn't have it. It's only offered when the switch handles every case. For a method that ends in ifs that test every case and exit (if (pet is Cat) return 1; else if (pet is Dog) return 2; else if (pet is Bird) return 3;), it adds the throw after them instead.
Adds required to a settable or init property, or a field that isn't readonly, so whoever creates the object has to set it. Constructors that already assign it (themselves, or through : this(...)) get [SetsRequiredMembers], so code that calls them still compiles. Only offered where the member, and its setter, are at least as visible as its type, which required needs. Not offered when a constructor that assigns it leaves another required member unset (the attribute would say it sets that one too), when a base type has required members, when a constructor that needs the attribute is in another file, or for a partial property.
Removes a dead switch expression arm, or a dead case label. If the label is the only one in its section, the whole section goes, unless the section declares a local variable or local function that other sections could use. For UN0016, removes the throwing discard arm.
Replaces pet.Value with pet, as the switch's input or in a test. It's titled "Switch on 'pet'" for a switch and "Test 'pet'" for a test.
Rewrites the code to look at what the union holds: (object)pet is Cat becomes pet is Cat, ((object)pet) switch becomes pet switch (and switch ((object)pet) becomes switch (pet)), (object)pet as Cat becomes pet.Value as Cat, (Cat)(object)pet becomes (Cat)pet.Value!, pet.Equals(cat) becomes object.Equals(pet.Value, cat), and pet.GetType() becomes pet.Value?.GetType().
Replaces the union with its Value: $"{pet}" becomes $"{pet.Value}", pet.ToString() becomes pet.Value?.ToString() ?? "" (without the ?? "" where what it's in deals with null already: ?? "none", ?.Length, or an interpolation), and a sequence pets becomes pets.Select(x => x.Value). For a nullable union, whose Value is the union, it writes maybe?.Value. Fix All adds the using System.Linq; a sequence needs once.
Adds public override string ToString() => Value?.ToString() ?? ""; to the union's declaration, giving a union Pet(Cat, Dog, Bird); a body first. Every place it's formatted then shows what it holds, so this fixes every UN0015 and UN0019 for the union at once. Offered for a union declared in the solution that doesn't declare its own ToString.