How to parse a string into a nullable int

Glenn Slaven picture Glenn Slaven · Sep 5, 2008 · Viewed 171.7k times · Source

I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.

I was kind of hoping that this would work

int? val = stringVal as int?;

But that won't work, so the way I'm doing it now is I've written this extension method

public static int? ParseNullableInt(this string value)
{
    if (value == null || value.Trim() == string.Empty)
    {
        return null;
    }
    else
    {
        try
        {
            return int.Parse(value);
        }
        catch
        {
            return null;
        }
    }
}   

Is there a better way of doing this?

EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

Answer

Matt Hamilton picture Matt Hamilton · Sep 5, 2008

int.TryParse is probably a tad easier:

public static int? ToNullableInt(this string s)
{
    int i;
    if (int.TryParse(s, out i)) return i;
    return null;
}

Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints.