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?
You can call compilation.ClassifyConversion(source, target)
and check whether the result's Kind
is ConversionKind.ImplicitReference
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With