Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could also make an extension method for this purpose;</p> <pre><code>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; } } </code></pre> <p>I've made this an extension on the <code>object</code> type, but it could equally well be on <code>string</code>. Personally I like these parser-extensions to be available on any object hence the extension on <code>object</code> instead of <code>string</code>.</p> <p>Example of use:</p> <pre><code>[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)); } </code></pre> <p>The downside would be that this breaks with the frameworks syntax for parsing values;</p> <pre><code>int.TryParse(input, out output)) </code></pre> <p>But I like the shorter version of it (whether it's more readable or not might be subject to discussion);</p> <pre><code>input.TryParse(out output) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload