dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.09k stars 4.04k forks source link

IEventSymbol.DeclaringSyntaxReferences Syntax is VariableDeclaratorSyntax not EventFieldDeclarationSyntax #74379

Closed LWehmschulteAtRosenxt closed 4 months ago

LWehmschulteAtRosenxt commented 4 months ago

Version Used: Microsoft.CodeAnalysis.CSharp" Version="4.9.2" Microsoft.CodeAnalysis.Analyzers" Version="3.3.4"

Steps to Reproduce:

  1. Create a class with a simple event declaration
  2. Get Event Symbols from class
// Dummy Class with Event
partial class SomeClass
{
    public event EventHandler? SomeEvent;
}
// SourceGenerator
private static void GetEvent(ITypeSymbol classSymbol) {
    classSymbol
        .GetAllMembers()
        .Where(x => x.Kind == SymbolKind.Event)
        .OfType<IEventSymbol>()
        .Where(x => x.DeclaredAccessibility == Accessibility.Public)
        .Where(x => !x.IsStatic)
        .ToList()
        .ForEach(evt =>
        {
            var syntax = evt.DeclaringSyntaxReferences.First().GetSyntax(); // VariableDeclaratorSyntax
        });
}

image

Expected Behavior: The syntax variable should be of type EventVieldDeclaration

Actual Behavior: See the syntax variable is of type VariableDeclaratorSyntax and not of type EventFieldDeclarationSyntax

CyrusNajmabadi commented 4 months ago

This is by design. Like fields, there can be multiple events declared in a single declaration. For example:

class C
{
    event Action A, B;
}

So the declaring syntax is the declarator.