How to parse a string into a nullable int in C# (.NET 3.5)

Posted by Glenn Slaven on Stack Overflow See other posts from Stack Overflow or by Glenn Slaven
Published on 2008-09-05T00:22:54Z Indexed on 2010/04/07 9:53 UTC
Read the original article Hit count: 322

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .net-3.5