Search code examples
.netroslynroslyn-code-analysis

Using Microsoft.CodeAnalysis how do you find references to a classes default instance constructor (section 10.11.4 of the C# 4)


I am using the following code to retrieve a list of all constructors from an ISymbol and I just noticed that classes without an explicit constructor show zero child nodes. My goal is to find all places where a class is instantiated (I am currently using Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync).

Is there some way to get a symbol for the auto-implemented constructor? If not is there some other way to find places where these classes are instantiated?

var ctors = dependant.DeclaringSyntaxReferences.SelectMany(
    r => r.GetSyntax().ChildNodes().Where(
        n => Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(n) == CSSyntaxKind.ConstructorDeclaration
        || Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(n) == VBSyntaxKind.ConstructorBlock));

Solution

  • I just found this which does exactly what I expected.

    INamedTypeSymbol.InstanceConstructors