skip to content

In C#, why does `status is not EmploymentStatus.Unemployed or EmploymentStatus.Student` still accept students, and what does the compiler report?

level: seniorimportance: should knowfreq 42%

answer

  1. pattern combinators have precedence
  2. not binds tightest
  3. then and, then or
  4. what the second alternative adds

basics

~20 s

Pattern combinators bind not first, then and, then or, so this means (not Unemployed) or Student, which every student already matches on the left. At C# 14 the compiler flags the redundant Student with warning CS9336; write not (Unemployed or Student).

solid answer

~40 s

C# binds pattern combinators in the order `not`, then `and`, then `or`. So `status is not EmploymentStatus.Unemployed or EmploymentStatus.Student` parses as `(not Unemployed) or Student`: a student already matches the left side, and the `Student` alternative adds nothing. The intended rule is `not (EmploymentStatus.Unemployed or EmploymentStatus.Student)`. At C# 14, the default for .NET 10 projects, the compiler reports warning CS9336, "The pattern is redundant.", on the second alternative; a project compiled as C# 13 or older gets no diagnostic. Ranges hit the same trap: `c is not >= 'a' and <= 'z'` means `(not >= 'a') and <= 'z'`, not "not a lowercase letter".

code

csharp · 12 lines
csharp
var status = EmploymentStatus.Student;

// Intended: neither unemployed nor a student
bool buggy = status is not EmploymentStatus.Unemployed or EmploymentStatus.Student;
bool fixedRule = status is not (EmploymentStatus.Unemployed or EmploymentStatus.Student);
Console.WriteLine($"{buggy} {fixedRule}");   // True False

char c = '{';
Console.WriteLine(c is not >= 'a' and <= 'z');     // False: (not >= 'a') and <= 'z'
Console.WriteLine(c is not (>= 'a' and <= 'z'));   // True: not a lowercase letter

enum EmploymentStatus { Employed, SelfEmployed, Student, Unemployed }

go deeper

for a junior

Remember the binding order not, then and, then or, and put parentheses around anything a not should cover.

for a middle

Explain how not A or B parses, why the B alternative is redundant, and why patterns use and, or and not instead of the Boolean operators.

for a senior

Diagnose rules that accept the wrong inputs from precedence slips, know that CS9336 appears only at C# 14, and add boundary tests for every enum member and range edge.

for a principal

Decide whether CS9336 breaks the build through warnings as errors, and plan the C# 14 upgrade so the new warnings are triaged rather than suppressed.

## Pattern combinators have their own precedence Since C# 9, patterns combine with three keywords: `not` negates a pattern, `and` requires both sides to match, and `or` requires either. Like operators in an expression, they bind with a fixed precedence: 1. `not` binds to the single pattern right after it. 2. `and` then joins its neighbours. 3. `or` binds last. A reader who knows `!`, `&&` and `||` tends to read a leading `not` as negating everything after it. It does not: `not A or B` is `(not A) or B`. ## Reading the buggy rule A loan rule meant to accept only applicants who are neither unemployed nor students was written as: ```csharp bool canApply = status is not EmploymentStatus.Unemployed or EmploymentStatus.Student; ``` | status | `(not Unemployed) or Student` (as written) | `not (Unemployed or Student)` (intended) | |---|---|---| | Employed | true | true | | SelfEmployed | true | true | | Student | true | false | | Unemployed | false | false | Every student is "not unemployed", so the left side already matches and the right side can never change the result. Nothing fails at run time: the expression returns a plausible `bool`, and only the student row of a test table exposes the slip. The fix is parentheses: `status is not (EmploymentStatus.Unemployed or EmploymentStatus.Student)`. ## What the compiler tells you At C# 14 the compiler checks `is` patterns, switch expressions and switch statements for alternatives that can never change the result, and reports warning **CS9336**, "The pattern is redundant.", on `EmploymentStatus.Student`. Points to know: - The check is gated on the language version: at C# 13 or earlier the same code compiles with no diagnostic. A .NET 10 project defaults to C# 14; a project targeting .NET 8 or .NET 9 defaults to C# 12 or C# 13 and stays silent. - It warns only where the redundant pattern sits to the right of a `not` inside a binary pattern, the shape this slip produces. Other redundant alternatives get a hidden diagnostic, so thorough but correct arms such as `< 0 => -1, 0 => 0, > 0 => 1` stay quiet. - Roslyn lists it among its compiler breaking changes for .NET 10: code that built cleanly gains a warning, and a build that treats warnings as errors then fails. ## The range variant The same precedence bites ranges. Meant as "not a lowercase letter": ```csharp char c = '{'; bool a = c is not >= 'a' and <= 'z'; // (not >= 'a') and <= 'z' -> false bool b = c is not (>= 'a' and <= 'z'); // not a lowercase letter -> true ``` The first line means "below 'a' and at most 'z'", which is just "below 'a'"; the `<= 'z'` part is redundant and draws CS9336 at C# 14. For `'{'`, which sorts after `'z'`, the two lines disagree. ## Patterns are not Boolean operators `and`, `or` and `not` look like `&&`, `||` and `!`, but they follow pattern rules: - `&&` and `||` are not allowed between patterns; `>= 18 && < 70` does not parse. - `is == 5` is CS9344, "The '==' operator is not supported in a pattern." `is != 5` is CS9345, which adds "Use 'not' to represent a negated pattern." - A variable cannot be declared under `not` or `or`: `o is int i or long` is CS8780, "A variable may not be declared within a 'not' or 'or' pattern." Under `and` it is fine. - The order in which patterns with the same binding level are checked is undefined; the compiler may test the right-hand side of an `or` first. No short-circuit order is promised. ## Habits that prevent it - Parenthesize whenever a pattern mixes `not` with `and` or `or`; the documentation recommends it for readability. - Prefer `not (A or B)` to listing what is allowed when the excluded set is shorter. - Keep CS9336 visible: a team that sets `TreatWarningsAsErrors` turns it into a build break, which is usually what you want for a rule this likely to be a bug. - Unit-test boundary values: one input per enum member, and characters just outside each range.

  • Can you declare a pattern variable inside an or alternative, as in o is int i or long?
    No. The SDK reports CS8780, "A variable may not be declared within a 'not' or 'or' pattern.", because the variable would be unassigned whenever the other alternative matched. Declarations are fine under `and`, as in `o is int i and > 3`, because both sides must match.
  • Does CS9336 catch every redundant alternative in a pattern?
    No. The compiler warns only when the redundant pattern sits to the right of a `not` in a binary pattern, the shape a precedence slip produces; other redundant alternatives get a hidden diagnostic so correct, deliberately thorough patterns stay quiet. It also needs C# 14. Boundary tests still matter.
  • Does the right side of an or pattern run only when the left side fails, as with ||?
    That is not promised. The order in which the compiler checks patterns at the same binding level is undefined, and it may test the right-hand side first. It is harmless for constants and relational patterns, but a getter or `Deconstruct` with side effects can run in an order you did not write.

  • not A or B in a pattern means neither A nor B.
  • A leading not negates the whole pattern that follows it.
  • The compiler has always warned about a redundant or alternative, whatever the language version.
  • and and or in patterns short-circuit left to right exactly like && and ||.
  • Writing is != 5 is the pattern way to say not 5.

Assumes C# 14 on the .NET 10 SDK: the CS9336 redundant-pattern warning is reported only at language version 14 or later, so C# 13 and older compile the same code silently.