Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - Is a INamedTypeSymbol of a class or subclass of a given type

Tags:

c#

roslyn

Using reflection, its pretty straightforward to determine whether an object is of a given class, using something like this:

(t == typeof(MyClass)) || (typeof(MyClass).IsAssignableFrom(t))

I'm trying to figure out how to do the same with Roslyn's code analysis APIs. I'm working with a loop like this, that attempts to find all local variable declarations in a solution.

foreach (var decl in rootNode.DescendantNodes().OfType<LocalDeclarationStatementSyntax>())
                {
                    var symbolInfo = semanticModel.GetSymbolInfo(decl.Declaration.Type);
                    var typeInfo = symbolInfo.Symbol as INamedTypeSymbol;
                    if (typeInfo == null)
                    {
                        continue;
                    }
                    // WHAT DO?

                }

I'm ultimately trying to build a list of all variables which are of a given type, or are of a subclass of a given type. It's easy enough to see how I could compare the name of the variable type to the name of the known type I am looking for - but I also need to handle the subclass case.

Is there a robust way to do this with Roslyn?

like image 527
kc9ddi Avatar asked Dec 10 '22 14:12

kc9ddi


1 Answers

You can call compilation.ClassifyConversion(source, target) and check whether the result's Kind is ConversionKind.ImplicitReference.

like image 130
SLaks Avatar answered Mar 30 '23 01:03

SLaks