Skip to content

Latest commit

 

History

History
54 lines (37 loc) · 2.38 KB

File metadata and controls

54 lines (37 loc) · 2.38 KB

MiKo_3233: Do not use var patterns for null checks

Cause

Code uses a var pattern (is var something) to match a value.

Rule description

Using is var something always succeeds, even when the value is null. That means something can be null and any access on it will throw a NullReferenceException. Instead, to avoid null, use a non-null pattern (such as is { } something), a specific type (such as is SomeType something), or add an explicit null check after the pattern match. This keeps your code safe and makes your intent clear.

Rationale behind

The var pattern looks like a safe way to capture a value, but it silently allows null to pass through. This mismatch between expectation and actual behavior can introduce subtle bugs that are hard to detect and diagnose.

Using null-safe alternatives instead of var patterns provides several important benefits:

  • Improved Safety: Null-safe patterns prevent null values from being used without an explicit check. This reduces the risk of unexpected NullReferenceException errors at runtime.

  • Clearer Intent: A non-null pattern or a type pattern clearly communicates that a valid, non-null value is expected. Readers immediately understand what the code is testing for.

  • Improved Readability: Patterns that express their intent directly are easier to read and reason about. There is no need to mentally track whether a bound variable might be null.

  • Reduced Cognitive Load: When a pattern guarantees a non-null value, developers do not need to keep track of potential null cases while reading through the code. This makes it easier to follow the logic.

  • Better Maintainability: Explicit null-safe patterns are less likely to be misunderstood or broken during future maintenance. The code's purpose is obvious without requiring deep knowledge of pattern matching semantics.

  • Fewer Hidden Bugs: The var pattern can silently accept null and pass it further into the code. Replacing it with a safer alternative eliminates an entire category of potential null-related bugs.

How to fix violations

To fix a violation of this rule, replace the var pattern with a non-null pattern, a specific type pattern, or add an explicit null check after the pattern match.

How to suppress violations

#pragma warning disable MiKo_3233
#pragma warning restore MiKo_3233