Convert int to enum

  • Thread starter Thread starter Shimon Sim
  • Start date Start date
S

Shimon Sim

I am writing general method that would take Type that should represent a
enum that do something with it.

In the middle of the method I need to cast it to this enum. I tried
Convert.ChangeType but it throws an exception - InvalidCast.

Wanted to know is it possible to make cast if you don't know the type at
the time of writing the code?

Thanks,
Shimon.
 
Shimon said:
I am writing general method that would take Type that should represent a
enum that do something with it.

In the middle of the method I need to cast it to this enum. I tried
Convert.ChangeType but it throws an exception - InvalidCast.

Wanted to know is it possible to make cast if you don't know the type at
the time of writing the code?
<snip>

What exactly do you need the "enum" for in the middle here ? Since you
can't write: EnumType eval = (EnumType)integerValue;

then I assume you want to do something like print it out, ie. the name
of the enum member instead of its integer value.

If that's what you want, you can do this:

Object value = Enum.ToObject(typeof(EnumType), integerValue);

and you can of course substitute "typeof(EnumType)" with any Type object
referring to an Enum type.
 
Champika Nirosh said:
I think you need to read about the enum data type.. I don't see a way to
convert a int to enum directly...

Shimon could write,

Enum.Parse( myEnumVar.GetType( ), myIntVar.ToString( ) );

but under normal circumstances he must eventually write an explicit
typecast when making the assignment. The only possible way around
it might be to use Reflection to set the value on a field member if that
were what myEnumVar were. For example,

// . . .
public class EnumCasting
{
public MyEnum settings;

public static void SetArbitraryEnumType( Type enumType, int enumValue)
{
this.GetType( ).GetField( "settings",
BindingFlags.Instance | BindingFlags.Public).SetValue(
this,
Enum.Parse( enumType, enumValue.ToString( ))
);
}
}
// . . .

This way Shimon doesn't absolutely need to know the Type of the
field named "settings" (if a field with the same name, but different enum
type, existed on multiple subclasses that could all inherit the method's
implementation ... bwawahwahwah ... that was a mouthful.) I'm not
saying this is a very good practice for class manageability in many
cases -- just that it's possible. :-)


Derek Harmon
 
Back
Top