I'm using enum circular reference to boil down some existing enums to a fewer values. It works well for my issue, since its a for a transitions period, where old enum values do occur in history, but no new entries with the obsolete values will be created.
I'm not looking for an alternative approach, but I stumbled upon this strange issue where the order of the enums, will affect the the serilized value in an unexpected manner.
I have this enum:
public enum CivilStatusEnum
{
None = 0,
Married = 1,
Cohabiting = Married,
Alone = 3,
DivorcedOrSeparated = Alone,
WidowOrWidower = Alone,
}
I assigned "DivorcedOrSeparated" = Alone (3). Now when I convert the enum to string I get the value "DivorcedOrSeparated".
Console.PrintLine(CivilStatusEnum.Alone.ToString());
Output:
DivorcedOrSeparated
I have an example code, with tests and their expected outcome. As you can see the test are failing. But If I change the order of the enums, the tests will parse.
[Theory]
[InlineData(CivilStatusEnum.Alone, "Alone")]
[InlineData(CivilStatusEnum.DivorcedOrSeparated, "Alone")]
[InlineData(CivilStatusEnum.WidowOrWidower, "Alone")]
[InlineData(CivilStatusEnum.None, "None")]
[InlineData(CivilStatusEnum.Married, "Married")]
[InlineData(CivilStatusEnum.Cohabiting, "Married")]
public void Test(CivilStatusEnum input, string expected)
{
var text = input.ToString();
text.Should().Be(expected);
}
I can't seem to find a rationel explanation for why the order matters for tostring and serilization.
Is this a bug in .NET 5, or am I missing something? If this behaviour is deliberate, how does it determind which enum name will be the output of tostring?
Thank you :)
