Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast int to enum?

How can an int be cast to an enum in C#?

like image 739
lomaxx Avatar asked Aug 27 '08 03:08

lomaxx


People also ask

How do I assign an integer to an enum?

Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .

Can you cast int to enum C++?

C++ Explicit type conversions Enum conversions static_cast can convert from an integer or floating point type to an enumeration type (whether scoped or unscoped), and vice versa. It can also convert between enumeration types.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Do you need to cast an enum to int?

You can create Enumeration without casting, it is not required.


1 Answers

From an int:

YourEnum foo = (YourEnum)yourInt; 

From a string:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);  // The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(",")) {     throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.") } 

Update:

From number you can also

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt); 
like image 175
FlySwat Avatar answered Sep 18 '22 14:09

FlySwat