Search code examples
c#new-operatorroslynmicrosoft.codeanalysis

Getting type of an ImplicitObjectCreationExpression


If I have an ImplicitObjectCreationExpression, how can I get the type that is being created using the SemanticModel?

My code:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

public static SemanticModel model;
public static ITypeSymbol GetCreationType (BaseObjectCreationExpressionSyntax boces) =>
    boces switch
    {
        ObjectCreationExpressionSyntax oces => model.GetSymbolInfo(oces.Type).Symbol!,
        ImplicitObjectCreationExpressionSyntax ioces => // ???
    };

Solution

  • Using sharplab.io, we can see that a statement such as

    object x = new();
    

    has a syntax tree like this (showing the new() part only):

    enter image description here

    The type that you want is a child of the "Operation" node, which you can get with SemanticModel.GetOperation. Then you can just get its Type.

    model.GetOperation(ioces).Type!