You could also make an extension method for this purpose;
public static bool TryParse(this object value, out int? parsed)
{
parsed = null;
try
{
if (value == null)
return true;
int parsedValue;
parsed = int.TryParse(value.ToString(), out parsedValue) ? (int?)parsedValue : null;
return true;
}
catch (Exception)
{
return false;
}
}
I've made this an extension on the object
type, but it could equally well be on string
. Personally I like these parser-extensions to be available on any object hence the extension on object
instead of string
.
Example of use:
[TestCase("1", 1)]
[TestCase("0", 0)]
[TestCase("-1", -1)]
[TestCase("2147483647", int.MaxValue)]
[TestCase("2147483648", null)]
[TestCase("-2147483648", int.MinValue)]
[TestCase("-2147483649", null)]
[TestCase("1.2", null)]
[TestCase("1 1", null)]
[TestCase("", null)]
[TestCase(null, null)]
[TestCase("not an int value", null)]
public void Should_parse_input_as_nullable_int(object input, int? expectedResult)
{
int? parsedValue;
bool parsingWasSuccessfull = input.TryParse(out parsedValue);
Assert.That(parsingWasSuccessfull);
Assert.That(parsedValue, Is.EqualTo(expectedResult));
}
The downside would be that this breaks with the frameworks syntax for parsing values;
int.TryParse(input, out output))
But I like the shorter version of it (whether it's more readable or not might be subject to discussion);
input.TryParse(out output)