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?
You can use the IsDefined
method to check if a value is among the defined values:
bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With