Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that integer type belongs to enum member

Tags:

c#

I want to check that some integer type belongs to (an) enumeration member.

For Example,

public enum Enum1 {     member1 = 4,      member2 = 5,      member3 = 9,      member4 = 0 } 

Enum1 e1 = (Enum1)4 gives me member1

Enum1 e2 = (Enum1)10 gives me nothing and I want to check it.

like image 341
Alexander Stalt Avatar asked Apr 09 '10 06:04

Alexander Stalt


People also ask

How do you find the enum value of an integer?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How can you tell if an enum is type?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.

Is int in enum C#?

By default, the type for enum elements is int. We can set different type by adding a colon like an example below. The different types which can be set are sbyte, byte, short, ushort, uint, ulong, and long.


2 Answers

Use Enum.IsDefined

Enum.IsDefined(typeof(Enum1), 4) == true 

but

Enum.IsDefined(typeof(Enum1), 1) == false 
like image 89
Samuel Neff Avatar answered Sep 29 '22 07:09

Samuel Neff


As Sam says, you can use IsDefined. This is somewhat awkward though. You may want to look at my Unconstrained Melody library which would let you us:

Enum1 e2 = (Enum1)10; if (e2.IsNamedValue()) // Will return false { } 

It's probably not worth it for a single enum call, but if you're doing a lot of stuff with enums you may find some useful things in there.

It should be quicker than Enum.IsDefined btw. It only does a linear scan at the moment, but let me know if you need that to be improved :) (Most enums are small enough that they probably wouldn't benefit from a HashSet, but we could do a binary search...)

like image 26
Jon Skeet Avatar answered Sep 29 '22 08:09

Jon Skeet