Skip to content

Enum.Format change in behavior between .Net Framework and .Net 5 #56200

@ChrisVicary

Description

@ChrisVicary

Repro:

using System;

class Test
{
    [Flags]
    public enum TestEnum { None = 0, Item1 = 1, Item2 = 2, }

    static void Main()
    {
        Console.WriteLine(Enum.Format(typeof(TestEnum), (int)3, "G"));
    }
}

.NET Framework: Item1, Item2
.NET Core: 3


Description

While upgrading a project from .Net Framework 4.7.2 to .Net 5 and I noticed a difference in behavior of the EnumConverter.ConvertToString() method when passing an integer value that could represent a combination of flags enum values. Here is some code that reproduces the problem:

class Program
{
	[Flags]
	public enum TestEnum { None = 0, Item1 = 1, Item2 = 2, }
            
	static void Main(string[] args)
	{
		var none = TestEnum.None;
		var single = TestEnum.Item1;
		var multiple = TestEnum.Item1 | TestEnum.Item2;

		Console.WriteLine(none);
		Console.WriteLine(single);
		Console.WriteLine(multiple);

		var converter = new EnumConverter(typeof(TestEnum));
		Console.WriteLine(converter.ConvertToString(none));
		Console.WriteLine(converter.ConvertToString(single));
		Console.WriteLine(converter.ConvertToString(multiple));

		Console.WriteLine(converter.ConvertToString((int)none));
		Console.WriteLine(converter.ConvertToString((int)single));
		Console.WriteLine(converter.ConvertToString((int)multiple));
		Console.ReadLine();
	}
}

Creating a simple console app with the code above, if I compile and run the app against .Net Framework 4.8 the last line outputs:
Item1, Item 2
If I compile and run against .Net 5 the last line outputs:
3

I tried to have a look through the code here, compared to reference source and I see quite a few differences in there, but couldn't quite nail down the path that the code is taking to just return the int value as a string rather than calculating the enum value and converting that.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions