C# Convert A Value To Enum

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Convert a value (int, string) to enum

1
Convert a value (int, string) to enum
What's a quick and easy way to cast an int to an enum in C#?
1. From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
From an int:
YourEnum foo = (YourEnum)yourInt;
Update : From number you can also:
YourEnum foo = Enum.ToObject(typeof(YourEnum) , yourInt);

2. Just cast it:
MyEnum e = (MyEnum)3;
You can check if it's in range using Enum.IsDefined:
if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

3. I am using this piece of code to cast int to my enum:
if (typeof(YourEnum).IsEnumDefined(valueToCast))
return (YourEnum)valueToCast;
else { //handle it here, if its not defined }
I find it the best solution.
4. 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. }
Convert a value (int, string) to enum

2
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.
5. Casting should be enough. If you're using C# 3.0 you can make a handy extension
method to parse enum values:
public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
Type type = typeof(TEnum);

if (value == null)
{
throw new ArgumentException("Value is null or empty.", "value");
}

if (!type.IsEnum)
{
throw new ArgumentException("Enum expected.", "TEnum");
}

return (TEnum)Enum.Parse(type, value.ToString(), true);
}
6. Hope this helps
if (Enum.IsDefined(typeof(foo), value.ToString()))
{
return (Foo)Enum.Parse(typeof(foo), value.ToString());
}

You might also like