dotnet/roslyn

CS0219 not working for non-primitive types

Open

#81743 opened on Dec 17, 2025

View on GitHub
 (5 comments) (1 reaction) (0 assignees)C# (20,414 stars) (4,257 forks)batch import
Area-CompilersConcept-Diagnostic Clarityhelp wanted

Description

Version Used: .NET 9.0.308

Steps to Reproduce:

  1. Activate analysis rule CS0219, set to warning.
  2. Create code with assignment to a non-primitive variable that is not used later.

In the snippet and screenshot below, the initializations of num1 and num2 are correctly flagged by CS0219. The initialization of violation2 should also be flagged, but it is not. The assignment to violation3 is flagged by IDE0059 (which should also catch violation2, so that one isn't working properly either.)

public async Task<Violation?> TestMethod(Guid violationId, CancellationToken cancellationToken)
{
    var violation1 = await this.violationStore.GetById(violationId, cancellationToken);
    int num1 = 0;

    try
    {
        var violation2 = await this.violationStore.GetById(violationId, cancellationToken);
        int num2 = 1;
    }
    catch (Exception)
    {
        return null;
    }

    var violation3 = await this.violationStore.GetById(violationId, cancellationToken);

    return violation1;
}

Diagnostic Id: CS0219: The variable 'variable' is assigned but its value is never used

Expected Behavior: Visual Studio should warn that the assigned value is unused, even for non-primitive types.

Actual Behavior: No warning is issued for the primitive types.

Contributor guide