Why does enum.ToString() give a different result than what's shown in the debugger tooltip?

StackOverflow https://stackoverflow.com/questions/2052551

  •  20-09-2019
  •  | 
  •  

Question

Test program (.NET 2.0):

[Flags]
enum MyEnum
{
    Member1 = 1,
    Member2 = 2,
}

class Program
{
    // Inspecting r shows "Member1 | Member2"
    MyEnum r = MyEnum.Member1 | MyEnum.Member2;

    // s = "Member1, Member2"
    string s = r.ToString();
}

I would have expected .ToString() to return a string with the members separated by a pipe, but that's not the case.

Bonus info: calling Enum.Parse() on the comma-separated string succeeds, while supplying it with a pipe-separated string fails.

Was it helpful?

Solution

The VS debugger uses visualizers to display values. Only if there's no visualizer for a specific datatype, it will fallback to the .ToString() method.

More info on visualizers:

http://msdn.microsoft.com/en-us/library/zayyhzts.aspx

OTHER TIPS

The default ToString implementation for an enum marked with FlagsAttribute is a comma-separated list. However, it is not necessarily the ToString result that is shown in the debugger - there must be a Debugger Visualizer set up for enums that renders the values with the bitwise OR symbol or pipe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top