The correct way to cast int to enumeration

Possible duplicate:
Insert int in Enum in C #

I am retrieving an int value from a database and want to pass the value of an enumeration variable. In 99.9% of cases, int will match one of the values ​​in the enumeration declaration.

public enum eOrderType {
    Submitted = 1,
    Ordered = 2,
    InReview = 3,
    Sold = 4,
    ...
}

eOrderType orderType = (eOrderType) FetchIntFromDb();

In the case of the edge, the value will not match (whether it distorts the data or does someone manually enter the system and mess with the data).

I could use the switch statement and catch defaultand correct the situation, but it feels wrong. There should be a more elegant solution.

Any ideas?

+3
source share
2 answers

You can do

int value = FetchIntFromDb();
bool ok = System.Enum.GetValues(typeof(eOrderType)).Cast<int>().Contains(value);

or rather, I will cache the results of GetValues ​​() in a static variable and use it again and again.

0

IsDefined, , :

bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
+5

All Articles