4

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 => // ???
    };
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36

2 Answers2

4

You want to call GetTypeInfo instead of GetSymbolInfo.

Jason Malinowski
  • 18,148
  • 1
  • 38
  • 55
3

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!
Sweeper
  • 213,210
  • 22
  • 193
  • 313