How do I cast int to enum in C#?
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 a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}
From a number:
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
Is it possible to cast integer to enum?
Yes, it's possible to cast Enum
to int
and vice versa, because every Enum
is actually represented by an int
per default. You should manually specify member values.
By default it starts from 0 to N.
It's also possible to cast Enum
to string
and vice versa.
public enum MyEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 3
}
private static void Main(string[] args)
{
int enumAsInt = (int)MyEnum.Value2; //enumAsInt == 2
int myValueToCast = 3;
string myValueAsString = "Value1";
MyEnum myValueAsEnum = (MyEnum)myValueToCast; // Will be Value3
MyEnum myValueAsEnumFromString;
if (Enum.TryParse<MyEnum>(myValueAsString, out myValueAsEnumFromString))
{
// Put logic here
// myValueAsEnumFromString will be Value1
}
Console.ReadLine();
}
C# int to enum conversion
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.
Casting ints to enums in C#
Guessing about 'why' is always dangerous, but consider this:
enum Direction { North =1, East = 2, South = 4, West = 8 }
Direction ne = Direction.North | Direction.East;
int value = (int) ne; // value == 3
string text = ne.ToString(); // text == "3"
When the [Flags]
attribute is put in front of the enum, that last line changes to
string text = ne.ToString(); // text == "North, East"
Integer to enum casting in C#
Let's say your enum
is this:
enum E {
A = 1
B = 2
C = 4
D = 8
}
If you translate each value to it's binary value, you get:
A = 0001
B = 0010
C = 0100
D = 1000
Now let's say you try to convert 12
, 1100
in binary, to this enum
:
E enumTest = (E)12;
It will output C|D
|
being the OR operator, C|D
would mean 0100 OR 1000
, which gives us 1100
, or 12
in decimal.
In your case, it's just trying to find which enum
combination is equal to 67239937
. This is converted to binary as 100000000100000000000000001
. This then converts to Test2|Test16|Test20
or 1|(1 << 17)|(1 << 26)
.
How to cast int to enum instead of using switch
For mathOperation
, all you need to do is cast int
to MathOperation
. However, I suggest you add definition 0 as "Undefined" in MathOperation
for readability.
For userInputDifficulty
, the easiest way could be using Dictionary
.
Set up your dictionary somewhere ( mostly when class is instantiated)
Dictionary<string, UserDifficulty> dict = new Dictionary<string, UserDifficulty>();
dict.Add( "E", UserDifficulty.Easy );
dict.Add( "N", UserDifficulty.Normal );
dict.Add( "H", UserDifficulty.Hard );
Replace your switch case with dictionary:
// This is an example.
string userInputDifficulty = "E";
UserDifficulty diff = dict[ userInputDifficulty ];
Cast Int to Generic Enum in C#
The simplest way I have found is to force the compiler's hand by adding a cast to object
.
return (T)(object)i.Value;
Why can't I cast an integer to an enumeration
I tested around a little bit and observed that the cast succeeds if the original value is an Int32
but fails if it is (for example) an Int64
or a byte
.
My suggestes solution is to use Convert.ToInt32()
before the cast:
AddedTask.Status = (TaskStatus) Convert.ToInt32(row.Cells["status"].Value);
From docs.microsoft.com:
An enumeration is a set of named constants whose underlying type is any integral type. If no underlying type is explicitly declared, Int32 is used.
So your TaskStatus
enum is derived from Int32
and direct casts from any other integral types will fail.
Cast integer to enum type with Flags attribute
So, two things you have to worry about. One (which I think you already realize) is that your underlying enum type is int32, and your value is uint16, so a conversion will need to happen somewhere. Two, you have to construct the enum type.
StatusWord looks like a constructor (similar to a union case member), but it's not. So here are two ways to do it with your uint16 value, and a third way to do it which is much better for readability, if you can do it that way.
let value = 0b1000001001us
// use F# enum operator
let flags1 = enum<StatusWord> (int value)
// use static Enum class
let flags2 = Enum.Parse(typeof<StatusWord>, string value) :?> StatusWord
// do bitwise stuff, of course now the compiler knows what you're doing
let flags3 = StatusWord.DATAPROCESS ||| StatusWord.PACKETSIZEERROR ||| StatusWord.DONOTRETRY
Because there are multiple ways, I had to refresh my memory, which I did at
https://fsharpforfunandprofit.com/posts/enum-types/
which is highly recommended reading (that article and the rest of that blog - it's how many people learn F#).
Related Topics
All Possible Array Initialization Syntaxes
How to Detect the Encoding/Codepage of a Text File
How to Write Unicode Characters to the Console
How to Suspend Painting For a Control and Its Children
Most Efficient Way to Concatenate Strings
Ignore Folders/Files When Directory.Getfiles() Is Denied Access
Recursion, Parsing Xml File With Attributes into Treeview C#
Load a Wpf Bitmapimage from a System.Drawing.Bitmap
Textboxfor Displaying Initial Value, Not the Value Updated from Code
How to Find the Method That Called the Current Method
How Do Parameterized Queries Help Against SQL Injection
Why Would You Use Expression≪Func≪T≫≫ Rather Than Func≪T≫
Listing All Permutations of a String/Integer