Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether class is a record using Roslyn

Tags:

c#

roslyn

record

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?

like image 973
mbabramo Avatar asked Sep 26 '20 11:09

mbabramo


1 Answers

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.

like image 145
Jason Malinowski Avatar answered Oct 11 '22 01:10

Jason Malinowski