Determine whether class is a record using Roslyn
Asked Answered
K

2

7

I am writing a source generator and need to know whether a class that I am adding functionality to with Microsoft.CodeAnalysis is a record.

I can do this by switching to the syntax model, like this:

public static bool IsRecord(this ITypeSymbol type)
{
    if (type == null || type.TypeKind != TypeKind.Class)
        return false;
    bool isRecord = (type.DeclaringSyntaxReferences.Any(x => (x.SyntaxTree.GetRoot().FindNode(x.Span) is RecordDeclarationSyntax)));
    return isRecord;
}

But is there any way to do this with the semantic model? I may well be missing something obvious, but I've checked what seem to me to be the obvious places, and I've also searched on github. It seems that there is an internal IsRecord within Roslyn, but I can't find anything publicly exposed. If I do not have access to this in the semantic model, will the above work even if the type is from code imported from another assembly?

Kilar answered 26/9, 2020 at 11:13 Comment(2)
So this is actually an open question for the Roslyn API that we're currently working on; if you don't mind me asking, why did you need to know if it was a record or not?Fogbow
@JasonMalinowski Source generation. When adding code to a class, I must include "partial record" or "partial class". For an example where this would be useful, see this code (not written by me).Kilar
F
2

Starting with 3.9.0-2.final version of the Roslyn API (this corresponds to Visual Studio 16.9 Preview 2), ITypeSymbol now has a IsRecord property you can use.

Fogbow answered 8/1, 2021 at 3:38 Comment(0)
K
1

There does not appear to be any official public property IsRecord. So we are left to look for what a record would contain, such as an implicitly declared property named "EqualityContract":

type.GetMembers().Any(x => x.Kind == SymbolKind.Property && x.Name == "EqualityContract" && x.IsImplicitlyDeclared)
Kilar answered 27/9, 2020 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.