0

On this page following code is suggested to find classes which derive from a given type, but this code does not work because following line

var symbol = _model.GetDeclaredSymbol(node);

returns ISymbol, rather than expected INamedTypeSymbol.

On the answers to FAQs on this page , for getting the type of a variable declaration, following piece of code is suggested. However, this also throws an exception in run-time, saying that cast to ILocalSymbol is not valid.

var type = ((ILocalSymbol)model.GetDeclaredSymbol(variableDeclarator)).Type;

I tried looking into Roslyn source code to figure out a way and tried them but so far no success.

What I would like to do is, detect all classes in a solution which derive from DbContext class of EntityFramework. Can anybody suggest me a way to find this? Thanks in advance!

Community
  • 1
  • 1
tubakaya
  • 457
  • 4
  • 15
  • What node are you operating on? What does `GetDeclaredSymbol` return? – SLaks Jul 19 '15 at 20:01
  • Thank you for your answer, I realized what the problem was. The node parameter sent to GetDeclaredSymbol method was not dynamically dispatched correctly. That's why it was calling the wrong overload of GetDeclaredSymbol. So I deleted the question. – tubakaya Jul 19 '15 at 20:46

1 Answers1

3

Figured what was going wrong. Maybe will help somebody else not to lose much time.

ModelExtensions class in Microsoft.CodeAnalysis namespace has a method declaration with the name GetDeclaredSymbol. The method that needed to be called was the one in class CSharpExtensions in namespace Microsoft.CodeAnalysis.CSharp. If you already have a using statement to Microsoft.CodeAnalysis in the class, GetDeclaredSymbol method on ModelExtensions is called, which was the case for me. Took me time to figure out.

This method in CSharpExtensions class is the one that should be invoked:

public static INamedTypeSymbol GetDeclaredSymbol(
  this SemanticModel semanticModel, 
  BaseTypeDeclarationSyntax declarationSyntax, 
  CancellationToken cancellationToken = default(CancellationToken));
Karel Frajták
  • 4,389
  • 1
  • 23
  • 34
tubakaya
  • 457
  • 4
  • 15
  • 1
    GetDeclaredSymbol is typed as returning an ISymbol, but the returned symbol will implement some more specific type, like INamedTypeSymbol. All those helpers do is just cast it specifically -- you can always just do an 'is' or 'as' check with a more specific base type. – Jason Malinowski Jul 21 '15 at 00:23
  • Thanks you so much – Celimpilo Mncwango Jun 01 '18 at 11:15