Roslyn: detect when a local variable has been declared with `using`

366 Views Asked by At

I'm writing a C# source generator (similar to analyzer) and I'm trying to determine if a local variable (ILocalSymbol) is readonly due to being declared with a using directive. Specifically the following case:

using System;

struct Container : IDisposable
{
    public void Dispose() {}
}

public class C {
    public void M() {
        using (var container = new Container())
        {
            var otherCon = new Container();
            
            // I want to detect when the following would throw an error
            //container = otherCon;
        }
    }
}

Roslyn doesn't seem to have any public APIs for this as far as I can tell. LocalSymbol has IsUsing but that is an internal type. Same deal with DeclarationKind.

1

There are 1 best solutions below

0
On

The only way I found to do this was by examining the declaring syntax for the variable:

var isWritable = true;
var declaringSyntax = symbol.OriginalDefinition.DeclaringSyntaxReferences.FirstOrDefault();
if (declaringSyntax?.GetSyntax().Parent is VariableDeclarationSyntax 
  variableDeclarationSyntax && variableDeclarationSyntax?.Parent is UsingStatementSyntax)
    isWritable = false;