-2

Something amazed me with Enum String Conversion

If I do:

(Edit: This assertion is contested - it is true only if an enum variable instance has an invalid value)

Convert.ToString(MyEnum.MyEnumValue); // Returns Integer Representation

Whereas if I do

MyEnum.MyEnumValue.ToString(); // Returns `MyEnumValue`

Why is this behaviour or am I missing something?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208

2 Answers2

2

I checked code that should be run for both cases. For Enum.ToString:

public override string ToString()
{
    return Enum.InternalFormat((RuntimeType)base.GetType(), this.GetValue());
}
private static string InternalFormat(RuntimeType eT, object value)
{
    if (eT.IsDefined(typeof(FlagsAttribute), false))
    {
        return Enum.InternalFlagsFormat(eT, value);
    }
    string name = Enum.GetName(eT, value);
    if (name == null)
    {
        return value.ToString();
    }
    return name;
}

For Convert.ToString:

this.GetType().ToString();

So, it should work in a same way for both cases. Please provide your code. Here is sample from my side.

Anton
  • 9,682
  • 11
  • 38
  • 68
0

As per Anton's answer, the behaviour of Convert.ToString and .ToString() are on an enum is identical.

I believe what may have happened is that you assigned the enum variable an integral value which is out of range of the enumeration. Since enums are internally represented as integral types, the backing type will generally have a much wider range than the enum states that have been defined for it.

Corruption of enum values can occur quite easily, for example during casting, during a deserialization step, or when using enum parsing methods.

As a result, you should always validate that the enum is valid before trusting it in the rest of your system, e.g. through Enum.IsDefined, although you'll need to do further work if you are using FlagsAttribute

enum MyEnum
{
   Value1 = 1,
   Value2 = 2
};

void Main()
{
    // Literal
    Console.WriteLine(Convert.ToString(MyEnum.Value1)); // Value1
    Console.WriteLine(MyEnum.Value1.ToString()); // Value1

    // Variable
    MyEnum myEnum = MyEnum.Value2;
    Console.WriteLine(Convert.ToString(myEnum)); // Value2
    Console.WriteLine(myEnum.ToString());  // Value2

    // Invalid
    MyEnum badEnum = (MyEnum)123;
    Console.WriteLine(Convert.ToString(badEnum)); // 123
    Console.WriteLine(badEnum.ToString()); // 123
}
StuartLC
  • 104,537
  • 17
  • 209
  • 285