You can 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 made this extension for type object , but it could also be on string . Personally, I like these parser extenders for any object, therefore extending to object instead of string .
Usage example:
[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 disadvantage would be that it violates the syntax of the parsing of values;
int.TryParse(input, out output))
But I like the shorter version (more readable or not, it can be a subject of discussion);
input.TryParse(out output)
Kjetil Klaussen Jun 28 '13 at 7:28 2013-06-28 07:28
source share