-1
[flags]
enum Test
{
  a=0,
  b=1,
  c=2
}
...
var v = Test.c | Test.b;
var str = v.ToString();
// str = 'b, c'

is the order of the values in 'str' defined. Both b, c and c, b are semantically the same by syntactically different. Why do I care - I am writing test code (not in c#) would prefer to not have to do fancy logic parsing all possible combinations

pm100
  • 48,078
  • 23
  • 82
  • 145
  • 5
    Wouldn't it be faster to actually write the tests than typing up a question here on SO and wait for someone to test it for you? – Peter Lillevold Sep 29 '14 at 19:10
  • Why ToString() to begin with? – Mikko Viitala Sep 29 '14 at 19:12
  • Please clarify your question, and then explain why you are trying to do this? – Jonathan Wood Sep 29 '14 at 19:15
  • You can add attribute and create own ToString (as extension method). More (you can base on it): http://stackoverflow.com/questions/25147228/sort-enums-in-declaration-order/25147851#25147851 –  Sep 29 '14 at 19:24
  • 1
    @Peter Lillevold, no it would not be, I can run a test and see that it comes back B,C. What does that mean? , that enums come back in alphabetical order, or order they were declared, some locale specific thing, something depending on what .net version.... – pm100 Sep 29 '14 at 19:36
  • @Mikko becuase my test code is running in javascript on a different machine – pm100 Sep 29 '14 at 19:37
  • always interesting to see questions that get upvoted and downvoted. – pm100 Sep 29 '14 at 20:55

1 Answers1

5

The documentation for Enum.ToString says

If the FlagsAttribute is applied and there is a combination of one or more named constants equal to the value of this instance, then the return value is a string containing a delimiter-separated list of the names of the constants.

It does not specify in what order they will be shown.

The code that does the formatting (see the function InternalFlagsFormat in the reference source, here: http://referencesource.microsoft.com/#mscorlib/system/enum.cs) appears to always work the same way.

But, because the order isn't documented, you'll have to judge for yourself how likely it is to change. Having been burned in the past by assuming that things wouldn't change, I'd be real wary of depending on anything that's not explicitly documented.

EDIT by OP: there is an interesting comment in the code that formats the output

 // These values are sorted by value. Don't change this
    String[] names;
    ulong[] values;

this suggests that the enum names will come out in order of the enum values. Although as you say - its not guranteed from version to version

pm100
  • 48,078
  • 23
  • 82
  • 145
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351