tags:

views:

168

answers:

1

Criteria: Performance, Performance, Performance.

I need a way to convert a uint, int, etc into it's enum equivalent. What's the fastest way I can do that using C#?

+12  A: 

Why can't you just do a direct cast?

MyEnum enumVar = (MyEnum)intVar;
Charles Graham
Argg, was just gonna say that :)
leppie
I know. That happens to me all the time. ;)
Charles Graham
Thanks! Wow, that was much easier then some other weird solutions I saw out there.
danmine
Enums to and from ints is trivial. In fact, I'm pretty sure that the compiler handles 99% of any optimizations that you would need to worry about. Now when you go back and forth from strings is where it can get funky.
Charles Graham
The only problem with this is that you can cast values that are invalid and you won't get an exception. Enum.Parse() is much safer, but it does involve overhead from a performance perspective.
OJ