Search code examples
c#.netroslyn-code-analysis

Is there any way of checking if an enum has an object value defined in it?


Here is the enum that I have defined:

enum LogicalChange
{
    List = SyntaxKind.List,
    TildeToken = SyntaxKind.TildeToken,
    ExclamationToken = SyntaxKind.ExclamationToken,
    DollarToken = SyntaxKind.DollarToken,
    PercentToken = SyntaxKind.PercentToken,
    CaretToken = SyntaxKind.CaretToken,
    AmpersandToken = SyntaxKind.AmpersandToken,
    AsteriskToken = SyntaxKind.AsteriskToken,
    MinusToken = SyntaxKind.MinusToken,
    PlusToken = SyntaxKind.PlusToken,
    EqualsToken = SyntaxKind.EqualsToken
}

I have a set of commands that should execute only if change.After.Parent.Kind() (which returns a SyntaxKind) is defined in the enum LogicalChange.

What I have tried so far is - Enum.IsDefined(typeof(LogicalChange), change.After.Parent.Kind()) but this generates an exception. I don't want to do string comparison. Is there any other way of achieving this?


Solution

  • It is not a simple name or string comparison, you need to cast it to the Enum Type you are comparing it to. This should not trigger an exception:

    if (Enum.IsDefined(typeof(LogicalChange), (LogicalChange)change.After.Parent.Kind()))
    {
    }