Roslyn: Check for Enum with CodeAnalysis

Created on 19 Dec 2018  路  2Comments  路  Source: dotnet/roslyn

Version Used:
Microsoft.CodeAnalysis.Analyzers.2.6.1
Description:
I have the Issue that i want to generate TypeScript from C# Model Classes. Therefore, I have to check, whether the Type of the Property is an Enum with only reading the current Model Class.
What the Property looks like:
public Sex Sex { get; set; }
What the Sex-Class looks like:

public enum Sex : int
    {
        Male = 0,
        Female = 1,
    }

If it is recognized as an Enum, following line in TypeScript should be generated:
import { Sex } from '../enums/sex';
instead of:
import { Sex, SexSchema } from './sex.model';

So how does one check for Enum-Type with roslyn?

Area-SDK and Samples Question

Most helpful comment

In this case @jmarolf he's starting with teh property, but trying to figure out the return type's meaning. So the Syntax itself isn't that helpful.

@NicolasBrandes I would recommend gitter.im/dotnet/roslyn for future one-off 'i need help' questions :)

For this one, here's what you would do:

Given a SemanticModel, call 'GetDeclaredSymbol' on the PropertyDeclarationSyntax you have. From that, you will get an IPropertySymbol back. This symbol has a 'Type' property telling you the return type of the property. From that ITypeSymbol you can call get it's 'TypeKind' and check if it's an enum. Putting it all together, you have:

((IPropertySymbol)semanticModel.GetDeclaredSymbol(propDeclSyntax)).Type.TypeKind == TypeKind.Enum

All 2 comments

I would recommend using the syntax visualizer to see what enums are represented as.

You can use the roslyn code quoter to see how to generate specific syntax

In this case @jmarolf he's starting with teh property, but trying to figure out the return type's meaning. So the Syntax itself isn't that helpful.

@NicolasBrandes I would recommend gitter.im/dotnet/roslyn for future one-off 'i need help' questions :)

For this one, here's what you would do:

Given a SemanticModel, call 'GetDeclaredSymbol' on the PropertyDeclarationSyntax you have. From that, you will get an IPropertySymbol back. This symbol has a 'Type' property telling you the return type of the property. From that ITypeSymbol you can call get it's 'TypeKind' and check if it's an enum. Putting it all together, you have:

((IPropertySymbol)semanticModel.GetDeclaredSymbol(propDeclSyntax)).Type.TypeKind == TypeKind.Enum

Was this page helpful?
0 / 5 - 0 ratings