Enum.TryParse reads like a safe way to turn a string into an enum. It returns a bool, it never throws on bad input, and it sits right at the point where untrusted text enters your system. So most code treats true as “this is one of my values, and it is the one the caller named.”
Neither half of that is guaranteed. TryParse is a general conversion routine with a generous definition of what a valid input looks like, and that definition has nothing to do with whether your enum has [Flags].
This article shows what the method really accepts, why the usual Enum.IsDefined guard misses the worst case, how the same behaviour reaches your API through JSON and query strings, and how to parse strictly. Every result below was run on .NET 10.
The enum for every example
A plain status enum. No attributes, no bit tricks, and values that C# numbers automatically:
public enum OrderStatus
{
Pending, // 0
Paid, // 1
Shipped, // 2
Refunded, // 3
}
The C# language reference confirms the numbering: associated values start with zero and increase by one in definition order. Nothing about this declaration looks like a bit field, which is what makes the first trap so easy to miss.
Trap 1: the comma
The documentation for Enum.TryParse says the input can be a single name or number, or a list delimited by commas. It also says what happens to a list: the result reflects the values “combined with a bitwise OR operation.”
That rule does not mention [Flags], and it does not depend on it:
Enum.TryParse<OrderStatus>("Paid, Shipped", out var status);
// returns true
// status == OrderStatus.Refunded
Paid is 1. Shipped is 2. 1 | 2 is 3, and 3 is Refunded. The caller sent two names, and neither of them was the value you ended up with.
If that string reaches code that filters a report, it returns the wrong rows. If it reaches code that moves an order to a new state, the order is now refunded. The same arithmetic applies to any enum numbered this way, including one that holds roles or permission levels.
Why IsDefined doesn’t catch it
The standard advice for validating a parsed enum is Enum.IsDefined, and the TryParse documentation itself recommends it for undefined numbers. It answers one question: does this value match a named constant?
For the comma case, the honest answer is yes:
Enum.IsDefined(OrderStatus.Refunded); // true
The value is wrong, but it is a real member. The guard checks the result, and the result looks perfect. Information about what the caller actually typed was thrown away during parsing, so no check on the parsed value can recover it.
This is the key distinction. IsDefined is a decent check for the next trap and no check at all for this one.
Trap 2: numbers that match nothing
The documentation is explicit about this one too. If the input is the string form of an integer that doesn’t represent a member, the method “returns an enumeration member whose underlying value is value converted to an integral type.”
| Input | Returns | Value | IsDefined |
|---|---|---|---|
"3" | true | Refunded | true |
"99" | true | (OrderStatus)99 | false |
"-1" | true | (OrderStatus)(-1) | false |
"+2" | true | Shipped | true |
" 2 " | true | Shipped | true |
"99999999999" | false | Pending | n/a |
IsDefined handles "99" and "-1". It does nothing about "3" and "+2", which may matter just as much: if your contract says callers send names, a number is a contract violation that your API quietly accepts. Once a client depends on it, the numeric values of your enum are part of your public interface, and reordering the members changes what those requests mean.
Trap 3: the smaller surprises
Whitespace is fine. The documentation says blank spaces can precede or follow each value, name or comma, so " Paid " parses to Paid. A second system that compares the raw string, a cache key for instance, sees a different value than the one you parsed.
Case depends on the overload. TryParse<TEnum>(string, out TEnum) is case-sensitive, so "paid" fails. TryParse<TEnum>(string, bool, out TEnum) lets you ignore case. JsonStringEnumConverter, covered next, reads case-insensitively. The same word can succeed in a request body and fail in your own parsing code.
A failed parse still gives you a value. When parsing fails, the output holds the default value of 0. In this enum that is Pending, a perfectly legitimate state:
Enum.TryParse("Refundd", out OrderStatus status); // return value ignored
// status == OrderStatus.Pending
Discard the return value, and a typo becomes a real status with no error anywhere.
Enum.Parse shares the rules. The Enum.Parse documentation describes the same comma lists and undefined integers. Only failures differ: it throws ArgumentException for an unknown name and OverflowException for a number outside the underlying type.
How this reaches your API
You may never call TryParse directly. Your framework can do the equivalent for you. Here is what each common entry point did with the same three inputs:
| Entry point | Paid, Shipped | 3 | 99 |
|---|---|---|---|
Enum.TryParse | Refunded | Refunded | (OrderStatus)99 |
JsonStringEnumConverter, default | Refunded | Refunded | (OrderStatus)99 |
JsonStringEnumConverter, allowIntegerValues: false | Refunded | rejected | rejected |
| Minimal API query parameter | Refunded | Refunded | (OrderStatus)99 |
MVC [ApiController] query parameter | Refunded | Refunded | 400 |
The JSON rows used string inputs. A bare JSON number behaves the same way: 99 is accepted by the default converter and rejected with allowIntegerValues: false. Without any converter, System.Text.Json represents enums as numbers, so it accepted 99 as well and refused the string "Paid".
Read the first column again. The comma passed every entry point. The option most people reach for, allowIntegerValues: false, closes the numeric door and leaves that one open. It also has a side effect on the way out: per the constructor documentation, the parameter controls whether undefined values are allowed, and in my test serializing (OrderStatus)99 then threw a JsonException instead of writing 99.
Validation attributes don’t help here either. [EnumDataType(typeof(OrderStatus))] rejected 99 and accepted the combined value, for the same reason IsDefined does. The automatic 400 from [ApiController] only fires when something marks the model state invalid, and for the comma nothing did.
Treat the table as a snapshot of one framework version, not as a contract. Most of these binding details aren’t documented, which is one more reason to own the check. Run your own endpoints against these three strings.
The fix: look names up instead of parsing them
Every trap above comes from using a conversion routine as a validator. If the contract is “the caller sends exactly one member name,” the honest implementation is a dictionary lookup. There’s nothing to split, combine, trim or convert:
using System.Collections.Frozen;
public static class StrictEnum<TEnum> where TEnum : struct, Enum
{
private static readonly FrozenDictionary<string, TEnum> Names =
Enum.GetNames<TEnum>().ToFrozenDictionary(
name => name,
name => Enum.Parse<TEnum>(name),
StringComparer.Ordinal);
public static bool TryParse(string? input, out TEnum value)
{
if (input is not null && Names.TryGetValue(input, out value))
return true;
value = default;
return false;
}
}
| Input | Enum.TryParse | StrictEnum.TryParse |
|---|---|---|
"Paid" | Paid | Paid |
"Paid, Shipped" | Refunded | rejected |
"3" | Refunded | rejected |
"99" | (OrderStatus)99 | rejected |
" Paid " | Paid | rejected |
"paid" | rejected | rejected |
Enum.Parse is safe in the initializer because the keys come from Enum.GetNames. FrozenDictionary is available from .NET 8. On older targets, use an ordinary Dictionary that you never modify after building it. If your API should accept any casing, change the comparer to StringComparer.OrdinalIgnoreCase, and make that a decision rather than an accident.
Wiring it into JSON
A small converter puts the same rule on request bodies:
public sealed class StrictEnumConverter<TEnum> : JsonConverter<TEnum>
where TEnum : struct, Enum
{
public override TEnum Read(
ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) =>
reader.TokenType == JsonTokenType.String
&& StrictEnum<TEnum>.TryParse(reader.GetString(), out var value)
? value
: throw new JsonException($"Not a valid {typeof(TEnum).Name}.");
public override void Write(
Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToString());
}
With this converter, "Paid" is accepted, while "paid", "Paid, Shipped", "3", 3, 99 and null all raise JsonException.
Wiring it into query strings
The simplest option is to bind the parameter as a string and parse it yourself:
app.MapGet("/orders", (string status) =>
StrictEnum<OrderStatus>.TryParse(status, out var parsed)
? Results.Ok(FindOrders(parsed))
: Results.BadRequest());
If you repeat this often, a small wrapper type with a static TryParse method keeps it tidy. Minimal APIs bind custom types through that method on route, query and header sources, and return 400 when it returns false.
How to choose
Pick by what the input is allowed to be:
- Exactly one name from an external caller: use a strict lookup. This covers most API fields, query filters and message payloads.
- Numbers from an old contract: accept them deliberately. Check
IsDefinedon a value you parsed as an integer, so a comma can’t get in, and pin the enum’s values explicitly so a reorder can’t change their meaning. - A true
[Flags]enum: combinations are the point, so comma lists may be legitimate.IsDefinedis the wrong check there because it rejects valid combinations. Validate against a mask of all known bits instead. - Trusted internal text, such as your own configuration:
Enum.Parseis fine. Its forgiving behaviour is a convenience when you control the input and a crash on a bad name is what you want.
Then add one test per enum boundary that sends "A, B", a defined number and an undefined number, and asserts each is rejected. Tests like these document your contract, and they will tell you if a framework upgrade changes the behaviour in the table above.
Summary
Enum.TryParseandEnum.Parsecombine comma-separated names with a bitwise OR on every enum, with or without[Flags]."Paid, Shipped"can land on a different, fully defined member.Enum.IsDefinedand[EnumDataType]can’t see the problem, because the result is valid.- Numeric strings parse too, including numbers that match no member.
IsDefinedcatches only the undefined ones. - A failed parse leaves 0 in the output, which may be a meaningful state. Never discard the return value.
- JSON converters and model binding inherit this behaviour.
allowIntegerValues: falseblocks numbers and not commas. - When the contract is one name, look the name up. Don’t convert it.
The method does what its documentation says. The bug is asking a converter to do a validator’s job.