Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check If a Enum contain a number?

Tags:

c#

.net

enums

I have a Enum like this:

 public enum PromotionTypes {     Unspecified = 0,      InternalEvent = 1,     ExternalEvent = 2,     GeneralMailing = 3,       VisitBased = 4,     PlayerIntroduction = 5,     Hospitality = 6 } 

I want to check if this Enum contain a number I give. For example: When I give 4, Enum contain that, So I want to return True, If I give 7, There isn't 7 in this Enum, So it returns False. I tried Enum.IsDefine but it only check the String value. How can I do that?

like image 774
Jack Zhang Avatar asked Sep 06 '12 01:09

Jack Zhang


People also ask

Can enums contain numbers?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


2 Answers

The IsDefined method requires two parameters. The first parameter is the type of the enumeration to be checked. This type is usually obtained using a typeof expression. The second parameter is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.

enum Status {     OK = 0,     Warning = 64,     Error = 256 }  static void Main(string[] args) {     bool exists;      // Testing for Integer Values     exists = Enum.IsDefined(typeof(Status), 0);     // exists = true     exists = Enum.IsDefined(typeof(Status), 1);     // exists = false      // Testing for Constant Names     exists = Enum.IsDefined(typeof(Status), "OK");      // exists = true     exists = Enum.IsDefined(typeof(Status), "NotOK");   // exists = false } 

SOURCE

like image 91
John Woo Avatar answered Oct 04 '22 16:10

John Woo


Try this:

IEnumerable<int> values = Enum.GetValues(typeof(PromotionTypes))                               .OfType<PromotionTypes>()                               .Select(s => (int)s); if(values.Contains(yournumber)) {       //... } 
like image 40
horgh Avatar answered Oct 04 '22 16:10

horgh