Recipe 15.5 · C#
Safe Parsing and Conversion
Problem
Values arrive as strings from query strings, CSV files, config and old database columns. The code converts them with int.Parse, Convert.ToDecimal or a try/catch helper. Bad input either crashes the request or turns silently into zero. And on a server with a different regional setting, "1,5" and "1.5" swap meaning.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: exceptions for control flow, culture-dependent.
public static int GetInt(string s)
{
try { return int.Parse(s); }
catch { return 0; }
}
public static decimal GetDecimal(object o)
{
if (o == null || o == DBNull.Value) return 0;
return Convert.ToDecimal(o); // uses the current culture
}
The improved recipe
using System;
using System.Globalization;
namespace ImproveCode.Utilities;
public static class SafeParse
{
private static readonly CultureInfo Invariant =
CultureInfo.InvariantCulture;
public static T? Value<T>(
string? text, IFormatProvider? provider = null)
where T : struct, IParsable<T> =>
T.TryParse(text?.Trim(), provider ?? Invariant, out T result)
? result
: null;
public static int? Int(string? text) =>
int.TryParse(
text, NumberStyles.Integer, Invariant, out int result)
? result
: null;
public static decimal? Decimal(
string? text, IFormatProvider? provider = null) =>
decimal.TryParse(
text, NumberStyles.Number, provider ?? Invariant,
out decimal result)
? result
: null;
public static DateOnly? Date(
string? text, params string[] formats)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
string[] accepted = formats.Length > 0
? formats
: ["yyyy-MM-dd"];
return DateOnly.TryParseExact(
text.Trim(), accepted, Invariant,
DateTimeStyles.None, out DateOnly result)
? result
: null;
}
public static bool? Bool(string? text) =>
text?.Trim().ToUpperInvariant() switch
{
"TRUE" or "T" or "YES" or "Y" or "1" or "ON" => true,
"FALSE" or "F" or "NO" or "N" or "0" or "OFF" => false,
_ => null
};
public static TEnum? EnumValue<TEnum>(string? text)
where TEnum : struct, Enum
{
if (Enum.TryParse(text?.Trim(), true, out TEnum result)
&& Enum.IsDefined(result))
{
return result;
}
return null;
}
}
Usage snippet:
int pageSize = SafeParse.Int(query["size"]) ?? 25;
DateOnly? shipDate = SafeParse.Date(row[4], "yyyy-MM-dd", "M/d/yyyy");
if (shipDate is null)
{
errors.Add($"Line {lineNumber}: invalid ship date '{row[4]}'.");
}
Guid? id = SafeParse.Value<Guid>(form["id"]);
How it works
Every method returns a nullable value. null means "could not parse", which is different from zero, and the caller decides what to do: use a default with ??, record a validation error, or reject the request. Nothing is swallowed and no exception is thrown for ordinary bad input, which matters in import loops where exceptions cost real time.
Value<T> uses the generic math interface IParsable<T> (.NET 7 and later). One method covers int, long, Guid, DateTime, TimeSpan and any of your own types that implement the interface.
Culture is explicit. Machine-produced text, such as files, query strings, config values and APIs, should be parsed with the invariant culture. Text that a person typed in a localized UI should be parsed with that person's culture, passed in as provider. The one thing never to do is depend on the server's current culture. Rebuild the server of a nightly import with a German locale and "1.250" stops meaning one and a quarter and starts meaning one thousand two hundred fifty.
Date uses TryParseExact with a list of formats you accept. Loose parsing of 03/04/2026 guesses between March 4 and April 3; exact formats don't guess.
EnumValue adds an Enum.IsDefined check, because Enum.TryParse accepts any number: "42" parses into an enum that has no member 42.
Variations and pitfalls
IsDefinedreturnsfalsefor combined[Flags]values. For flags enums, drop the check or validate against the mask of all defined bits.- For database values, avoid this class entirely. Read typed values with
reader.GetInt32or let Dapper map them, as in Chapter 1.DBNullhandling belongs at the data boundary, not in a string parser. - If you need the reason a value failed, return a small result type (Chapter 5) instead of
null. - ASP.NET Core model binding already parses route and query values into typed parameters with the invariant culture. Use
SafeParsefor the places binding doesn't reach: files, config strings, legacy columns that store numbers as text.