13

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?

HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • Code doesn't make sense. You can cast an enum to a number, but not a number of an enum. Day of Week for zero should be DayOfWeek.Sunday not the number zero. – jdweng Jun 17 '16 at 23:33
  • I explicitly stated it was a coding style at the first sentence. Of course the code doesn't make sense. It was just to illustrate. I'm asking what is the purpose of Enum.ToObject(). What does it accomplish that simple casting does not? – HelloWorld Jun 17 '16 at 23:35
  • 1
    No idea, but the fact that this method was in .NET 1.1 might give a hint. There's a bunch of stuff from those days that really shouldn't be used anymore (looking at you `ArrayList`) – BradleyDotNET Jun 17 '16 at 23:41
  • Aha, yea. That is a good point. Well, I saw this style in a P/Invoke-library, so thought maybe it held some special significance. – HelloWorld Jun 17 '16 at 23:44

1 Answers1

17

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

Community
  • 1
  • 1
The Smallest
  • 5,713
  • 25
  • 38