Getting type of an ImplicitObjectCreationExpression

Viewed 63

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 => // ???
    };
2 Answers

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!

You want to call GetTypeInfo instead of GetSymbolInfo.

Related