Skip to content

Commit

Permalink
Fix Enum.Parse's parse failure exception to include value in error me…
Browse files Browse the repository at this point in the history
…ssage (#57945)
  • Loading branch information
stephentoub authored Aug 23, 2021
1 parent 331cfe3 commit 3863140
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/libraries/System.Private.CoreLib/src/System/Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,8 @@ private static bool TryParseRareEnum(RuntimeType enumType, ReadOnlySpan<char> va

private static bool TryParseByName(RuntimeType enumType, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out ulong result)
{
ReadOnlySpan<char> originalValue = value;

// Find the field. Let's assume that these are always static classes because the class is an enum.
EnumInfo enumInfo = GetEnumInfo(enumType);
string[] enumNames = enumInfo.Names;
Expand Down Expand Up @@ -952,7 +954,7 @@ private static bool TryParseByName(RuntimeType enumType, ReadOnlySpan<char> valu

if (throwOnFailure)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value.ToString()));
throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, originalValue.ToString()));
}

result = 0;
Expand Down
9 changes: 9 additions & 0 deletions src/libraries/System.Runtime/tests/System/EnumTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,15 @@ private static void Parse_Generic_Invalid<T>(Type enumType, string value, bool i
}
}

[Theory]
[InlineData("Yellow")]
[InlineData("Yellow,Orange")]
public static void Parse_NonExistentValue_IncludedInErrorMessage(string value)
{
ArgumentException e = Assert.Throws<ArgumentException>(() => Enum.Parse(typeof(SimpleEnum), value));
Assert.Contains(value, e.Message);
}

[Theory]
[InlineData(SByteEnum.Min, "Min")]
[InlineData(SByteEnum.One, "One")]
Expand Down

0 comments on commit 3863140

Please sign in to comment.