I am working on a C# code analyzer and use Roslyn (.NET Compiler API).
And I would like to check, that a particular type is inherited from a base class type.
For example, let's assume we have a hierarchy of custom classes:
TypeA -> TypeB -> TypeC -> TypeD
Where TypeA is parent class for TypeB, TypeB is parent for TypeC and TypeC is parent for TypeD.
I created a method:
bool InheritsFrom(ITypeSymbol symbol, string expectedParentTypeName)
{
while (true)
{
if (symbol.ToString().Equals(expectedParentTypeName))
{
return true;
}
if (symbol.BaseType != null)
{
symbol = symbol.BaseType;
continue;
}
break;
}
return false;
}
symbol contains the type, that should be checked. But this approach does not work. Code does not get the parent type for the symbol.
symbol.BaseType returns the same class type twice and then (on the next iteration) I get symbol.BaseType equal to null.
expectedParentTypeName contains fully qualified type name: for example some.namespace.blablabla.TypeC
How can I solve this task?
Update
As I noted above, let's assume we have a hierarchy:
TypeA -> TypeB -> TypeC -> TypeD
Upon analysis I get a property with type TypeD and I want to check, that it is inherited from TypeB
Update #2
TypeA -> TypeB -> TypeC -> TypeD types are not existing yet when I write my code analyser. So, I can't use typeof and other stuff for these types.
They will exist only in context the analyzer will work in.
My analyzer gets a part of the source code, recognizes it as a type name and I want to check, that this recognized type name is inherited from another custom type, imported from a custom nuget package.
All I have - I have source code to analyze and names of those custom types in class, property, field, etc declarations.
Update #3
For the following code:
SyntaxNodeAnalysisContext context; // is already initialized
PropertyDeclarationSyntax propertyDeclaration = (PropertyDeclarationSyntax)context.Node;
ClassDeclarationSyntax classDeclaration = (ClassDeclarationSyntax) propertyDeclaration.Parent;
TypeInfo propertyTypeInfo = context.SemanticModel.GetTypeInfo(propertyDeclaration);
TypeInfo classTypeInfo = context.SemanticModel.GetTypeInfo(classDeclaration);
propertyTypeInfo and classTypeInfo do not contain any information inside.
