Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way of casting an int to an enum [duplicate]

Tags:

c#

enums

Possible Duplicate:
Cast int to Enum in C#

I fetch a int value from the database and want to cast the value to an enum variable. In 99.9% of the cases, the int will match one of the values in the enum declaration

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

eOrderType orderType = (eOrderType) FetchIntFromDb();

In the edge case, the value will not match (whether it's corruption of data or someone manually going in and messing with the data).

I could use a switch statement and catch the default and fix the situation, but it feels wrong. There has to be a more elegant solution.

Any ideas?

like image 401
AngryHacker Avatar asked Mar 07 '11 19:03

AngryHacker


1 Answers

You can use the IsDefined method to check if a value is among the defined values:

bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
like image 150
Guffa Avatar answered Oct 06 '22 22:10

Guffa