I recently saw a project that was using this style:
(SomeEnum)Enum.ToObject(typeof(SomeEnum), some int)
instead of this style:
(SomeEnum)some int
Why use the former? Is it just a matter of style?
From MSDN:
This conversion method returns a value of type Object. You can then cast it or convert it to an object of type enumType.
https://msdn.microsoft.com/en-us/library/ksbe1e7h(v=vs.110).aspx
It seems to me that MSDN tells me that I should call ToObject(), and then I can cast. But I'm confused because I know I can cast without calling that method. What is the purpose of ToObject()? What does it accomplish that simple casting does not?
Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!
The ToObject(Type, Object) method converts the integral value value to an enumeration member whose underlying value is value . Note that the conversion succeeds even if value is outside the bounds of enumType members.
You can explicitly type cast an int to a particular enum type, as shown below.
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 .
In most cases simple cast is enough.
But sometimes you get type only in runtime.
Here comes Enum.ToObject
into play. It can be used in cases, when you need dynamically get enum values (or maybe metadata (attributes) attached to enum values).
Here is an simple example:
enum Color { Red = 1, Green, Blue }
enum Theme { Dark = 1, Light, NotSure }
public static void Main(string[] args)
{
var elements = new[]
{
new { Value = 1, Type = typeof(Color) },
new { Value = 2, Type = typeof(Theme) },
new { Value = 3, Type = typeof(Color) },
new { Value = 1, Type = typeof(Theme) },
new { Value = 2, Type = typeof(Color) },
};
foreach (var element in elements)
{
var enumValue = Enum.ToObject(element.Type, element.Value);
Console.WriteLine($"{element.Type.Name}({element.Value}) = {enumValue}");
}
}
Output is:
Color(1) = Red
Theme(2) = Light
Color(3) = Blue
Theme(1) = Dark
Color(2) = Green
More info on enum casting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With