Code example that demonstrates a fundamental flaw in Enum.TryParse<T>().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Code example that demonstrates a fundamental flaw in Enum.TryParse<T>(). | |
using System; | |
using System.Linq; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var values = new[] { | |
/* | |
// These strings are all parsed successfully by Enum.TryParse<System.DayOfWeek>(), as expected. | |
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", | |
"0", "1", "2", "3", "4", "5", "6", | |
*/ | |
/* | |
// These strings are all parsed successfully by Enum.TryParse<System.DayOfWeek>() -IF- case-insensitivity is enabled, as expected. | |
"MoNday", "TuEsday", "WeDnesday", "ThUrsday", "FrIday", "SaTurday", "SuNday", | |
*/ | |
// These strings are all parsed successfully by Enum.TryParse<System.DayOfWeek>(), even though they shouldn't be. | |
"55" | |
}; | |
var results = values.Select(x => | |
{ | |
var tryParseResult = Enum.TryParse<System.DayOfWeek>(x, true, out var parsedEnum); | |
return new { | |
String = x, | |
TryParseResult = tryParseResult, | |
ParsedEnum = parsedEnum | |
}; | |
}); | |
foreach (var result in results.OrderBy(x => x.TryParseResult)) | |
{ | |
Console.WriteLine($@"TryParse<System.DayOfWeek>(""{result.String}"") = {result.TryParseResult}"); | |
if (result.TryParseResult) Console.WriteLine($@"ParsedEnum = {result.ParsedEnum}"); | |
Console.WriteLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment