johnny 5
johnny 5

Reputation: 20987

Roslyn Check If Field Declaration has been assigned to

I'm writing an app which converts keys to use resources from a RESX File. This code was working with local variables before:

public static void AnalyzeConstDeclaration(SyntaxNodeAnalysisContext context)
{
    var fieldDeclaration = (FieldDeclarationSyntax)context.Node;

    if (false == IsValidFieldDeclaration(context, fieldDeclaration))
    {
        return;
    }

    var firstVariable = fieldDeclaration.Declaration.Variables.FirstOrDefault();
    var dataFlowAnalysis = context.SemanticModel.AnalyzeDataFlow(firstVariable);

    var variableSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);
    if (dataFlowAnalysis.WrittenOutside.Contains(variableSymbol))
    {
        return;
    }


    var firstSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);

    context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), firstSymbol.Name));
}

However when I try to get the dataFlowAnalysis I receive an error:

Additional information: statementOrExpression is not a StatementSyntax or an ExpressionSyntax.

How can Ideally just need to see if anyone has written to this variable outside of the declaration.

Upvotes: 2

Views: 697

Answers (1)

SLaks
SLaks

Reputation: 887195

DataFlow works by analyzing order of execution within a single method.
It doesn't make sense for class-level fields.

Instead, you should use a simple syntax visitor (or SymbolFinder) to search the entire class for assignments to the field.

You'll probably also want to check whether it's ever passed as a ref parameter.

Upvotes: 4

Related Questions