Casting for enumeration compared to Enum.ToObject

I recently saw a project that used this style:

(SomeEnum)Enum.ToObject(typeof(SomeEnum), some int) 

instead of this style:

 (SomeEnum)some int 

Why use the first one? Is this just a matter of style?

From MSDN:

This conversion method returns a value of type Object. Then you can pour 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 what I should call ToObject (), and then I can do it. But I'm confused because I know what I can use without calling this method. What is the purpose of ToObject ()? What does he do that simple casting doesn't?

+7
enums c #
source share
1 answer

In most cases, a simple cast is sufficient.

But sometimes you only get type at runtime. Enum.ToObject comes into play. It can be used in cases where you need to dynamically obtain enumeration values ​​(or, possibly, metadata (attributes) associated with enumeration values). Here is a 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}"); } } 

Exit:

 Color(1) = Red Theme(2) = Light Color(3) = Blue Theme(1) = Dark Color(2) = Green 

Read more about enum enumeration

+6
source share

All Articles