Fix Enum.Parse's parse failure exception to include value in error message (#57975)
authorgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Wed, 25 Aug 2021 02:07:14 +0000 (22:07 -0400)
committerGitHub <noreply@github.com>
Wed, 25 Aug 2021 02:07:14 +0000 (22:07 -0400)
Co-authored-by: Stephen Toub <stoub@microsoft.com>
src/libraries/System.Private.CoreLib/src/System/Enum.cs
src/libraries/System.Runtime/tests/System/EnumTests.cs

index ad0a684..6274258 100644 (file)
@@ -879,6 +879,8 @@ namespace System
 
         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;
@@ -952,7 +954,7 @@ namespace System
 
             if (throwOnFailure)
             {
-                throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value.ToString()));
+                throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, originalValue.ToString()));
             }
 
             result = 0;
index f718e6e..a764555 100644 (file)
@@ -288,6 +288,15 @@ namespace System.Tests
         }
 
         [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")]
         [InlineData(SByteEnum.Two, "Two")]