TryParse a string to a nullable type (DateTime, int, Decimal, etc)

Tags: .Net

When collecting information from a form and saving it to the database I often run into scenarios where I want to parse the user input into a Nullable Type as some of the fields in my database are nullable.  If you are trying to do the same the following generic method will get you up and running in no time.  This will help you parse a string to int? (nullable int), string to decimal?, string to DateTime? etc.

public static Nullable<T> TryParseStruct<T>(string input)
where T : struct
{
    Nullable<T> result = new Nullable<T>();
    if (string.IsNullOrEmpty(input))
        return result;

    try
    {
        IConvertible convertibleString = (IConvertible)input;
        result = new Nullable<T>((T)convertibleString.ToType(typeof(T), CultureInfo.CurrentCulture));
    }
    catch (InvalidCastException)
    {

    }
    catch (FormatException)
    {

    }

    return result;
}
Add a Comment