0

Say I have int val = 1; What is the best way to check whether or not that value corresponds with an enum. Here is a sample enum:

public enum AlertType 
{ 
    Success=1, 
    Warning=2, 
    Error=3 
};

I'm looking for an answer that has the best maintainability.

1
  • 1
    Are you looking for Enum::IsDefined Method ?? Commented Aug 29, 2013 at 19:17

5 Answers 5

9

I think you are looking for Enum::IsDefined Method

Returns an indication whether a constant with a specified value exists in a specified enumeration.

Updated:-

Try something like this:-

 if(Enum.IsDefined(typeof(AlertType), val)) {}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best answer. Please update your answer with the actual code: if(Enum.IsDefined(typeof(AlertType), val)) {}
1

This should work:

Int32 val = 1;
if (Enum.GetValues(typeof(AlertType)).Cast<Int32>().Contains(val))
{
}

Comments

0

You can cast you enum choices to an int for that check :

const int val = 1;
if (val == (int)AlertType.Success)
{
    // Do stuff
}
else if (val == (int) AlertType.Warning)
{
    // Do stuff
}
else if (val == (int) AlertType.Error)
{
    // Do stuff
}

8 Comments

I know I can do that, I was wondering if there was a better way.
Then your question should mention you're looking for something else.
@apfunk Then include what you tried and your expected output. Can't read minds.
@Pierre, but this is a demonstrably verbose and poor solution.
@ChrisSinclair hahaha sorry totally did not get it was sarcastic. Damn you interwebz
|
0

In addition to the other solutions offered, here's another easy way to check:

Enum.GetName(typeof(AlertType), (AlertType)val) != null

Comments

0
if (Enum.IsDefined(typeof(AlertType), x))
{
    var enumVal = Enum.Parse(typeof(AlertType), x.ToString());
}
else
{
    //Value not defined
}

1 Comment

Once you know it exists, you can just cast x to AlertType with (AlertType)x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.