Phase 6 of 30 · Topic 6.2

Code Analysis Attributes: `[NotNullWhen]`, `[MaybeNullWhen]` & `[MemberNotNull]`

1Concept

Helper validation methods require attributes from `System.Diagnostics.CodeAnalysis` to inform Roslyn's flow analyzer about conditional output nullability guarantees.

2Architecture Diagram

public static bool TryParse([NotNullWhen(true)] out string? result)
       │
  Returns true  ──> Roslyn guarantees `result` is non-null!
  Returns false ──> Roslyn expects `result` may be null.

3Code Example

C# 13 & .NET 9
using System;
using System.Diagnostics.CodeAnalysis;

public class NullAttributeDemo
{
    public static bool TryGetConfig(string key, [NotNullWhen(true)] out string? value)
    {
        if (key == "DB_CONN")
        {
            value = "Server=localhost;Database=Master;";
            return true;
        }
        value = null;
        return false;
    }

    public static void Main()
    {
        if (TryGetConfig("DB_CONN", out var connString))
        {
            // Zero compiler warning because [NotNullWhen(true)] informs Roslyn!
            Console.WriteLine($"Connection String Length: {connString.Length}");
        }
    }
}

4Expected Output

Connection String Length: 33

5Key Takeaways

  • Use `[NotNullWhen(true)]` on TryParse-style methods.
  • Use `[MemberNotNull(nameof(FieldName))]` in constructor initialization helper methods.
  • Attributes ensure library consumers get accurate compile-time diagnostics.