Dv6
Dv6

Reputation: 489

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?

Upvotes: 0

Views: 82

Answers (2)

hossein shaebani
hossein shaebani

Reputation: 19

IsDefined method allows to you to send three type as value:

  1. own enum type
  2. int
  3. string

so you can use these ways:

 1. Enum.IsDefined(typeof(LogicalChange), (LogicalChange)change.After.Parent.Kind())
 2. Enum.IsDefined(typeof(LogicalChange), (int)change.After.Parent.Kind())
 3. Enum.IsDefined(typeof(LogicalChange), change.After.Parent.Kind().ToString())
  • note: way no 3 is correct for you because you choose same name in both Enums, But it's better to not use it.

Upvotes: 1

Innat3
Innat3

Reputation: 3576

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()))
{
}

Upvotes: 2

Related Questions