Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# int to enum conversion [duplicate]

Tags:

c#

enums

Possible Duplicate:
Cast int to enum in C#

If I have the following code:

enum foo : int {     option1 = 1,     option2,     ... }  private foo convertIntToFoo(int value) {     // Convert int to respective Foo value or throw exception } 

What would the conversion code look like?

like image 664
TK. Avatar asked Feb 02 '09 11:02

TK.


2 Answers

It's fine just to cast your int to Foo:

int i = 1; Foo f = (Foo)i; 

If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.

If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:

int i = 1; if (Enum.IsDefined(typeof(Foo), i)) {     Foo f = (Foo)i; } else {    // Throw exception, etc. } 

However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.

Also note that you don't have to specify that your enum inherits from int; this is the default behavior.

like image 104
Jon B Avatar answered Oct 14 '22 17:10

Jon B


I'm pretty sure you can do explicit casting here.

foo f = (foo)value; 

So long as you say the enum inherits(?) from int, which you have.

enum foo : int 

EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.

You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.

enum (C# Reference)
Enumeration Types (C# Programming Guide)

like image 28
Cameron MacFarland Avatar answered Oct 14 '22 17:10

Cameron MacFarland