Skip to content

Instantly share code, notes, and snippets.

@jehrenzweig
Created September 11, 2019 21:36
Embed
What would you like to do?
Code example that demonstrates a fundamental flaw in Enum.TryParse<T>().
// 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