Skip to main content

Analyzers Overview

UnionGenerator includes powerful Roslyn analyzers that provide compile-time safety and help you write better union code. These analyzers catch common mistakes, ensure exhaustive pattern matching, and suggest improvements.

πŸ“¦ Available Analyzer Packages​

UnionGenerator.Analyzers​

The main analyzer package provides diagnostics and code fixes for:

  • Pattern matching completeness - Ensures all union cases are handled
  • Union factory method validation - Validates factory method signatures
  • ASP.NET Core integration - Detects misuse in controllers and minimal APIs
  • Debug visualization - Suggests adding debugger attributes
  • OneOf migration patterns - Helps migrate from OneOf library

Install via NuGet:

dotnet add package UnionGenerator.Analyzers

Automatic Installation​

The analyzers are automatically included when you install:

  • UnionGenerator (includes core analyzers)
  • UnionGenerator.AspNetCore (includes ASP.NET Core analyzers)

🎯 Why Use Analyzers?​

Compile-Time Safety​

Catch errors before they reach production:

var result = GetResult();

// ❌ Analyzer warning: Missing case handling
var value = result switch
{
{ IsSuccess: true } success => success.Value
// Missing error case - analyzer warns you!
};

Exhaustive Pattern Matching​

Ensure all union cases are covered:

[GenerateUnion]
public partial record PaymentStatus
{
public static partial PaymentStatus Pending();
public static partial PaymentStatus Completed(string transactionId);
public static partial PaymentStatus Failed(string reason);
}

// βœ… Analyzer ensures all cases are handled
var message = status.Match(
pending: () => "Processing...",
completed: tx => $"Success: {tx}",
failed: reason => $"Failed: {reason}"
);

Maintainability​

When you add new union cases, analyzers automatically warn you about missing handlers:

// You add a new case:
public static partial PaymentStatus Refunded(decimal amount);

// βœ… Analyzer immediately warns about all switch statements
// that don't handle the new 'Refunded' case

πŸ“Š Diagnostic Severity Levels​

SeverityIconDescription
ErrorπŸ”΄Code won't compile - must be fixed
Warning🟑Potential bug - should be fixed
InfoπŸ”΅Suggestion for improvement
HiddenβšͺAvailable but not shown unless configured

πŸ› οΈ Configuration​

Enable/Disable Specific Analyzers​

In your .editorconfig:

# Disable specific analyzer
dotnet_diagnostic.UG1001.severity = none

# Change severity level
dotnet_diagnostic.UG002.severity = error

# Set category-wide severity
dotnet_analyzer_diagnostic.category-Usage.severity = warning

Project-Wide Configuration​

In your .csproj:

<PropertyGroup>
<!-- Treat all analyzer warnings as errors -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

<!-- Disable specific diagnostics -->
<NoWarn>UG3001;UG3002</NoWarn>
</PropertyGroup>

Suppress in Code​

Use #pragma directives:

#pragma warning disable UG1001 // Incomplete pattern matching
var result = value switch
{
{ IsSuccess: true } => "OK",
_ => "Error" // Generic handler is intentional
};
#pragma warning restore UG1001

Or use attributes:

[SuppressMessage("UnionGenerator", "UG1001:Incomplete pattern matching")]
public string ProcessResult(Result result)
{
// ...
}

πŸ“‹ Diagnostic ID Reference​

IDSeverityDescriptionPackage
UG1001WarningIncomplete pattern matching in Match() callsCore
UG002WarningMissing union case in switch expressionsCore
UG3001InfoConsider using generated adapter for OneOfAnalyzers
UG3002InfoAdd debugger visualization attributesAnalyzers
UG4010InfoUnion not mapped to IActionResultASP.NET Core
UG4011InfoError case without status codeASP.NET Core
UG4012HiddenConvention override recommendedASP.NET Core
UG9002WarningNo union cases foundCore
UG9003WarningFactory method has multiple parametersCore
UG9004WarningDuplicate union case signatureCore

πŸš€ Quick Start​

  1. Install the analyzer package:
dotnet add package UnionGenerator.Analyzers
  1. Write union code:
[GenerateUnion]
public partial record ApiResponse
{
public static partial ApiResponse Success(Data data);
public static partial ApiResponse NotFound();
public static partial ApiResponse Error(string message);
}
  1. See warnings for incomplete matching:
// ⚠️ UG1001: Missing 'Error' case
var result = response.Match(
success: data => "OK",
notFound: () => "Not Found"
// Error case missing - analyzer warns!
);
  1. Apply code fix (Ctrl+. or Cmd+.):
// βœ… Fixed automatically by code fix provider
var result = response.Match(
success: data => "OK",
notFound: () => "Not Found",
error: message => $"Error: {message}"
);

πŸ” IDE Integration​

Visual Studio​

Analyzers appear as:

  • Squiggly underlines in the editor
  • Entries in the Error List window
  • Light bulb suggestions (Ctrl+.)

JetBrains Rider​

Analyzers integrate with:

  • ReSharper inspections
  • Solution-wide analysis
  • Code cleanup profiles

VS Code​

Requires C# extension (OmniSharp):

  • Inline diagnostics
  • Problems panel
  • Quick fix suggestions

πŸ“š Learn More​

πŸ’‘ Best Practices​

1. Treat Warnings as Errors in CI/CD​

<PropertyGroup>
<TreatWarningsAsErrors Condition="'$(Configuration)' == 'Release'">true</TreatWarningsAsErrors>
</PropertyGroup>

2. Use .editorconfig for Team Standards​

# Team-wide analyzer settings
[*.cs]
dotnet_diagnostic.UG1001.severity = error
dotnet_diagnostic.UG002.severity = error

3. Review Analyzer Warnings Regularly​

  • Don't suppress warnings without good reason
  • Document suppressions with comments
  • Periodically review suppressed diagnostics

4. Keep Analyzers Updated​

dotnet list package --outdated
dotnet add package UnionGenerator.Analyzers

πŸŽ“ Next Steps​