dotnet/roslyn

CS0219 not working for non-primitive types

Open

#81,743 建立於 2025年12月17日

在 GitHub 查看
 (5 留言) (1 反應) (0 負責人)C# (20,414 star) (4,257 fork)batch import
Area-CompilersConcept-Diagnostic Clarityhelp wanted

描述

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.

貢獻者指南