TypeInfo.IsAssignableFrom in Roslyn analyzer
Asked Answered
B

1

12

In my Roslyn analyzer I get Microsoft.CodeAnalysis.TypeInfo of an argument by

var argumentTypeInfo = semanticModel.GetTypeInfo(argumentSyntax.Expression);

also I have another instance of Microsoft.CodeAnalysis.TypeInfo called targetTypeInfo. Now I want to know if the type describled by targetTypeInfo is assignable from the type describled by argumentTypeInfo.

I know System.Reflection.TypeInfo has its IsAssignableFrom method, which is exactly what I want. But the convertion between the two TypeInfos is a problem. What's the correct way to get type relationships in an analyzer?

Blinker answered 24/2, 2017 at 4:48 Comment(1)
You can check the base classes and implemented interfaces of the ITypeSymbol in TypeInfo in question. But this might be cumbersome. Another approach which might work is to use the Compilation.ClassifyConversion and check the returned ConversionKind. A third option is to check how Roslyn binds the is operator: source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Binder/…, but I guess it uses the ClassifyConversion. Let me know if any of these worked.Corinthian
D
0

What Tamas commented was helpful. It goes in the direction of the solution I found.

Nowadays one can use the Compilation.HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType) method. This was discussed here https://github.com/dotnet/roslyn/issues/9461 and then added with PR #26719.

This does exactly what I wanted when I found this question.

Dunno answered 3/2 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.