using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace YourNameSpaceHere { public static class ToNullableStringExtension { /// /// More convenient than using T.TryParse(string, out T). /// Works with primitive types, structs, and enums. /// Tries to parse the string to an instance of the type specified. /// If the input cannot be parsed, null will be returned. /// /// /// If the value of the caller is null, null will be returned. /// So if you have "string s = null;" and then you try "s.ToNullable...", /// null will be returned. No null exception will be thrown. /// /// Contributed by Taylor Love (Pangamma) /// /// /// /// public static T? ToNullable(this string p_self) where T : struct { if (!string.IsNullOrEmpty(p_self)) { var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)); if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self); if (typeof(T).IsEnum) { T t; if (Enum.TryParse(p_self, out t)) return t;} } return null; } } }