public static class StringExtensions {
private delegate bool TypeParseDelegate<T>(string s, out T result);
private static T To<T>(string value, TypeParseDelegate<T> parse, T def = default) {
return parse(value?.Trim(), out var result) ? result : def;
}
private static T? ToNullable<T>(string value, TypeParseDelegate<T> parse) where T : struct {
T? ret = default;
if (parse(value?.Trim(), out var result)) {
ret = result;
}
return ret;
}
public static int ToInt32(this string value, int def = default) => To(value, int.TryParse, def);
public static float ToFloat(this string value, float def = default) => To(value, float.TryParse, def);
public static decimal ToDecimal(this string value, decimal def = default) => To(value, decimal.TryParse, def);
public static Guid ToGuid(this string value, Guid def = default) => To(value, Guid.TryParse, def);
public static int? ToInt32Nullable(this string value) => ToNullable<int>(value, int.TryParse);
public static float? ToFloatNullable(this string value) => ToNullable<float>(value, float.TryParse);
public static decimal? ToDecimalNullable(this string value) => ToNullable<decimal>(value, decimal.TryParse);
public static Guid? ToGuidNullable(this string value) => ToNullable<Guid>(value, Guid.TryParse);
public static DateTime? ToDatetimeNullable(this string value, string fmt = "yyyy-MM-dd") {
if (DateTime.TryParseExact(value?.Trim(), fmt, CultureInfo.CurrentCulture, DateTimeStyles.None, out var d)) {
return d;
} else {
return null;
}
}
}