10

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?

Community
  • 1
  • 1
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • Have you seen the other [Cast int to Enum Questions](http://www.google.com/search?q=cast+int+to+enum+site:stackoverflow.com)? – Metro Smurf Mar 07 '11 at 19:24
  • A general comment about using enums: Make sure you always include a default 0 value `public enum eOrderType { None = 0, Submitted = 1, ... }` – Metro Smurf Mar 07 '11 at 19:25
  • I think this is a slightly different question than the 'Cast int to Enum' question. As it happens, the second highest voted answer to that question is also a good answer to this question. – Daniel Pratt Mar 07 '11 at 19:29

2 Answers2

6

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

bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

You can do

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

or rather I would cache the GetValues() results in a static variable and use it over and over gain.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • 1
    That was my initial answer (basically), until I realised that there already is a method in the Enum class that does that... ;) – Guffa Mar 07 '11 at 21:58