<p>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.</p>

<p>I was kind of hoping that this would work</p>

<pre><code>int? val = stringVal as int?;
</code></pre>

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

<pre><code>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;
        }
    }
}   
</code></pre>

<p>Is there a better way of doing this?</p>

<p><strong>EDIT:</strong>  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?</p>

[{'answer_id': 45037, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 10, 'selected': True, 'text': '<p><code>int.TryParse</code> is probably a tad easier:</p>\n\n<pre><code>public static int? ToNullableInt(this string s)\n{\n    int i;\n    if (int.TryParse(s, out i)) return i;\n    return null;\n}\n</code></pre>\n\n<p><strong>Edit</strong> @Glenn <code>int.TryParse</code> is "built into the framework". It and <code>int.Parse</code> are <em>the</em> way to parse strings to ints.</p>\n'}, {'answer_id': 45039, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 3, 'selected': False, 'text': '<p>Try this:</p>\n\n<pre><code>public static int? ParseNullableInt(this string value)\n{\n    int intValue;\n    if (int.TryParse(value, out intValue))\n        return intValue;\n    return null;\n}\n</code></pre>\n'}, {'answer_id': 45066, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 8, 'selected': False, 'text': "<p>You can do this in one line, using the conditional operator and the fact that you can cast <code>null</code> to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of <code>TryParse</code>):</p>\n<p>Pre C#7:</p>\n<pre><code>int tempVal;\nint? val = Int32.TryParse(stringVal, out tempVal) ? tempVal : (int?)null;\n</code></pre>\n<p>With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.</p>\n<pre><code>int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;\n</code></pre>\n"}, {'answer_id': 45532, 'author': 'Murph', 'author_id': 1070, 'author_profile': 'https://Stackoverflow.com/users/1070', 'pm_score': 0, 'selected': False, 'text': "<p>You should <em>never</em> use an exception if you don't have to - the overhead is horrible.</p>\n\n<p>The variations on TryParse solve the problem - if you want to get creative (to make your code look more elegant) you could probably do something with an extension method in 3.5 but the code would be more or less the same.</p>\n"}, {'answer_id': 241962, 'author': 'Duckboy', 'author_id': 2724, 'author_profile': 'https://Stackoverflow.com/users/2724', 'pm_score': 5, 'selected': False, 'text': "<p>[<strong>Updated</strong> to use modern C# as per @sblom's suggestion]</p>\n\n<p>I had this problem and I ended up with this (after all, an <code>if</code> and 2 <code>return</code>s is soo long-winded!):</p>\n\n<pre><code>int? ToNullableInt (string val)\n    =&gt; int.TryParse (val, out var i) ? (int?) i : null;\n</code></pre>\n\n<p>On a more serious note, try not to mix <code>int</code>, which is a C# keyword, with <code>Int32</code>, which is a .NET Framework BCL type - although it works, it just makes code look messy.</p>\n"}, {'answer_id': 241977, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>\n</blockquote>\n\n<p>There isn't.</p>\n"}, {'answer_id': 1391080, 'author': 'umbyersw', 'author_id': 267578, 'author_profile': 'https://Stackoverflow.com/users/267578', 'pm_score': 0, 'selected': False, 'text': '<p>Using delegates, the following code is able to provide reusability if you find yourself needing the nullable parsing for more than one structure type. I\'ve shown both the .Parse() and .TryParse() versions here.</p>\n\n<p>This is an example usage:</p>\n\n<pre><code>NullableParser.TryParseInt(ViewState["Id"] as string);\n</code></pre>\n\n<p>And here is the code that gets you there...</p>\n\n<pre><code>public class NullableParser\n  {\n    public delegate T ParseDelegate&lt;T&gt;(string input) where T : struct;\n    public delegate bool TryParseDelegate&lt;T&gt;(string input, out T outtie) where T : struct;\n    private static T? Parse&lt;T&gt;(string input, ParseDelegate&lt;T&gt; DelegateTheParse) where T : struct\n    {\n      if (string.IsNullOrEmpty(input)) return null;\n      return DelegateTheParse(input);\n    }\n    private static T? TryParse&lt;T&gt;(string input, TryParseDelegate&lt;T&gt; DelegateTheTryParse) where T : struct\n    {\n      T x;\n      if (DelegateTheTryParse(input, out x)) return x;\n      return null;\n    }\n    public static int? ParseInt(string input)\n    {\n      return Parse&lt;int&gt;(input, new ParseDelegate&lt;int&gt;(int.Parse));\n    }\n    public static int? TryParseInt(string input)\n    {\n      return TryParse&lt;int&gt;(input, new TryParseDelegate&lt;int&gt;(int.TryParse));\n    }\n    public static bool? TryParseBool(string input)\n    {\n      return TryParse&lt;bool&gt;(input, new TryParseDelegate&lt;bool&gt;(bool.TryParse));\n    }\n    public static DateTime? TryParseDateTime(string input)\n    {\n      return TryParse&lt;DateTime&gt;(input, new TryParseDelegate&lt;DateTime&gt;(DateTime.TryParse));\n    }\n  }\n</code></pre>\n'}, {'answer_id': 1613379, 'author': 'John Dauphine', 'author_id': 195302, 'author_profile': 'https://Stackoverflow.com/users/195302', 'pm_score': 1, 'selected': False, 'text': '<p>I found and adapted some code for a Generic NullableParser class.  The full code is on my blog <a href="http://johndauphine.blogspot.com/2009/10/nullable-tryparse-function-in-c.html?m=1" rel="nofollow noreferrer">Nullable TryParse</a></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Globalization;\nnamespace SomeNamespace\n{\n    /// &lt;summary&gt;\n    /// A parser for nullable types. Will return null when parsing fails.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;\n    ///\n    public static class NullableParser&lt;T&gt; where T : struct\n    {\n        public delegate bool TryParseDelegate(string s, out T result);\n        /// &lt;summary&gt;\n        /// A generic Nullable Parser. Supports parsing of all types that implements the tryParse method;\n        /// &lt;/summary&gt;\n        /// &lt;param name="text"&gt;Text to be parsed&lt;/param&gt;\n        /// &lt;param name="result"&gt;Value is true for parse succeeded&lt;/param&gt;\n        /// &lt;returns&gt;bool&lt;/returns&gt;\n        public static bool TryParse(string s, out Nullable&lt;T&gt; result)\n        {\n            bool success = false;\n            try\n            {\n                if (string.IsNullOrEmpty(s))\n                {\n                    result = null;\n                    success = true;\n                }\n                else\n                {\n                    IConvertible convertableString = s as IConvertible;\n                    if (convertableString != null)\n                    {\n                        result = new Nullable&lt;T&gt;((T)convertableString.ToType(typeof(T),\n                            CultureInfo.CurrentCulture));\n                        success = true;\n                    }\n                    else\n                    {\n                        success = false;\n                        result = null;\n                    }\n                }\n            }\n            catch\n            {\n                success = false;\n                result = null;\n            }\n            return success;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 2426218, 'author': 'Leigh Bowers', 'author_id': 1415041, 'author_profile': 'https://Stackoverflow.com/users/1415041', 'pm_score': 0, 'selected': False, 'text': "<p>I realise this is an old topic, but can't you simply:</p>\n\n<pre><code>(Nullable&lt;int&gt;)int.Parse(stringVal);\n</code></pre>\n\n<p>?</p>\n"}, {'answer_id': 2603590, 'author': 'Daniel Ballinger', 'author_id': 54026, 'author_profile': 'https://Stackoverflow.com/users/54026', 'pm_score': 2, 'selected': False, 'text': '<p>The following should work for any struct type. It is based off code by <a href="http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/26a2d96a-468c-46cc-a0fb-bd2b52b6771e" rel="nofollow noreferrer">Matt Manela from MSDN forums</a>. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.</p>\n\n<pre><code>        public static bool TryParseStruct&lt;T&gt;(this string value, out Nullable&lt;T&gt; result)\n            where T: struct \n        {\n            if (string.IsNullOrEmpty(value))\n            {\n                result = new Nullable&lt;T&gt;();\n\n                return true;\n            }\n\n            result = default(T);\n            try\n            {\n                IConvertible convertibleString = (IConvertible)value;\n                result = new Nullable&lt;T&gt;((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));\n            }\n            catch(InvalidCastException)\n            {\n                return false;\n            }\n            catch (FormatException)\n            {\n                return false;\n            }\n\n           return true;\n        }\n</code></pre>\n\n<p>These were the basic test cases I used.</p>\n\n<pre><code>        string parseOne = "1";\n        int? resultOne;\n        bool successOne = parseOne.TryParseStruct&lt;int&gt;(out resultOne);\n        Assert.IsTrue(successOne);\n        Assert.AreEqual(1, resultOne);\n\n        string parseEmpty = string.Empty;\n        int? resultEmpty;\n        bool successEmpty = parseEmpty.TryParseStruct&lt;int&gt;(out resultEmpty);\n        Assert.IsTrue(successEmpty);\n        Assert.IsFalse(resultEmpty.HasValue);\n\n        string parseNull = null;\n        int? resultNull;\n        bool successNull = parseNull.TryParseStruct&lt;int&gt;(out resultNull);\n        Assert.IsTrue(successNull);\n        Assert.IsFalse(resultNull.HasValue);\n\n        string parseInvalid = "FooBar";\n        int? resultInvalid;\n        bool successInvalid = parseInvalid.TryParseStruct&lt;int&gt;(out resultInvalid);\n        Assert.IsFalse(successInvalid);\n</code></pre>\n'}, {'answer_id': 5392671, 'author': 'mortb', 'author_id': 599842, 'author_profile': 'https://Stackoverflow.com/users/599842', 'pm_score': 4, 'selected': False, 'text': '<p>Old topic, but how about:</p>\n\n<pre><code>public static int? ParseToNullableInt(this string value)\n{\n     return String.IsNullOrEmpty(value) ? null : (int.Parse(value) as int?);\n}\n</code></pre>\n\n<p>I like this better as the requriement where to parse null, the TryParse version would not throw an error on e.g. ToNullableInt32(XXX). That may introduce unwanted silent errors.</p>\n'}, {'answer_id': 5420250, 'author': 'orcun', 'author_id': 67756, 'author_profile': 'https://Stackoverflow.com/users/67756', 'pm_score': 1, 'selected': False, 'text': '<p>I felt I should share mine which is a bit more generic.</p>\n\n<p>Usage:</p>\n\n<pre><code>var result = "123".ParseBy(int.Parse);\n\nvar result2 = "123".ParseBy&lt;int&gt;(int.TryParse);\n</code></pre>\n\n<p>Solution:</p>\n\n<pre><code>public static class NullableParse\n{\n    public static Nullable&lt;T&gt; ParseBy&lt;T&gt;(this string input, Func&lt;string, T&gt; parser)\n        where T : struct\n    {\n        try\n        {\n            return parser(input);\n        }\n        catch (Exception exc)\n        {\n            return null;\n        }\n    }\n\n    public delegate bool TryParseDelegate&lt;T&gt;(string input, out T result);\n\n    public static Nullable&lt;T&gt; ParseBy&lt;T&gt;(this string input, TryParseDelegate&lt;T&gt; parser)\n        where T : struct\n    {\n        T t;\n        if (parser(input, out t)) return t;\n        return null;\n    }\n}\n</code></pre>\n\n<p>First version is a slower since it requires a try-catch but it looks cleaner. If it won\'t be called many times with invalid strings, it is not that important.\nIf performance is an issue, please note that when using TryParse methods, you need to specify the type parameter of ParseBy as it can not be inferred by the compiler. I also had to define a delegate as out keyword can not be used within Func&lt;>, but at least this time compiler does not require an explicit instance.</p>\n\n<p>Finally, you can use it with other structs as well, i.e. decimal, DateTime, Guid, etc. </p>\n'}, {'answer_id': 6424685, 'author': 'Lyskespark', 'author_id': 808355, 'author_profile': 'https://Stackoverflow.com/users/808355', 'pm_score': 3, 'selected': False, 'text': '<p>I feel my solution is a very clean and nice solution:</p>\n\n<pre><code>public static T? NullableParse&lt;T&gt;(string s) where T : struct\n{\n    try\n    {\n        return (T)typeof(T).GetMethod("Parse", new[] {typeof(string)}).Invoke(null, new[] { s });\n    }\n    catch (Exception)\n    {\n        return null;\n    }\n}\n</code></pre>\n\n<p>This is of course a generic solution which only require that the generics argument has a static method "Parse(string)".  This works for numbers, boolean, DateTime, etc.</p>\n'}, {'answer_id': 6474962, 'author': 'Michael', 'author_id': 222748, 'author_profile': 'https://Stackoverflow.com/users/222748', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p><strong>Glenn Slaven</strong>: I\'m more interested in knowing if\n  there is a built-in framework method\n  that will parse directly into a\n  nullable int?</p>\n</blockquote>\n\n<p>There is this approach that will parse directly to a nullable int (and not just int) if the value is valid like null or empty string, but does throw an exception for invalid values so you will need to catch the exception and return the default value for those situations:</p>\n\n<pre><code>public static T Parse&lt;T&gt;(object value)\n{\n    try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }\n    catch { return default(T); }\n}\n</code></pre>\n\n<p>This approach can still be used for non-nullable parses as well as nullable:</p>\n\n<pre><code>enum Fruit { Orange, Apple }\nvar res1 = Parse&lt;Fruit&gt;("Apple");\nvar res2 = Parse&lt;Fruit?&gt;("Banana");\nvar res3 = Parse&lt;int?&gt;("100") ?? 5; //use this for non-zero default\nvar res4 = Parse&lt;Unit&gt;("45%");\n</code></pre>\n\n<p><strong>NB:</strong> There is an IsValid method on the converter you can use instead of capturing the exception (thrown exceptions does result in <a href="http://www.developerfusion.com/article/5250/exceptions-and-performance-in-net/" rel="noreferrer">unnecessary overhead</a> if expected). Unfortunately it only works since .NET 4 but there\'s still an issue where it doesn\'t check your locale when validating correct DateTime formats, see <a href="http://connect.microsoft.com/VisualStudio/feedback/details/93559/typeconverter-for-value-types-such-as-int-bool-short-etc-return-true-to-isvalid-even-if-the-value-is-not-valid" rel="noreferrer">bug 93559</a>.</p>\n'}, {'answer_id': 8077089, 'author': 'Pavel Hodek', 'author_id': 519856, 'author_profile': 'https://Stackoverflow.com/users/519856', 'pm_score': 3, 'selected': False, 'text': '<p>You can forget all other answers - there is a great generic solution:\n<a href="http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/" rel="noreferrer">http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/</a></p>\n\n<p>This allows you to write very clean code like this:</p>\n\n<pre><code>string value = null;\nint? x = value.ConvertOrDefault();\n</code></pre>\n\n<p>and also:</p>\n\n<pre><code>object obj = 1;  \n\nstring value = null;\nint x = 5;\nif (value.TryConvert(out x))\n    Console.WriteLine("TryConvert example: " + x); \n\nbool boolean = "false".ConvertOrDefault();\nbool? nullableBoolean = "".ConvertOrDefault();\nint integer = obj.ConvertOrDefault();\nint negativeInteger = "-12123".ConvertOrDefault();\nint? nullableInteger = value.ConvertOrDefault();\nMyEnum enumValue = "SecondValue".ConvertOrDefault();\n\nMyObjectBase myObject = new MyObjectClassA();\nMyObjectClassA myObjectClassA = myObject.ConvertOrDefault();\n</code></pre>\n'}, {'answer_id': 20065814, 'author': 'Qi Luo', 'author_id': 2514803, 'author_profile': 'https://Stackoverflow.com/users/2514803', 'pm_score': 2, 'selected': False, 'text': '<p>This solution is generic without reflection overhead.</p>\n\n<pre><code>public static Nullable&lt;T&gt; ParseNullable&lt;T&gt;(string s, Func&lt;string, T&gt; parser) where T : struct\n{\n    if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;\n    else return parser(s);\n}\n\nstatic void Main(string[] args)\n{\n    Nullable&lt;int&gt; i = ParseNullable("-1", int.Parse);\n    Nullable&lt;float&gt; dt = ParseNullable("3.14", float.Parse);\n}\n</code></pre>\n'}, {'answer_id': 29169616, 'author': 'wmoecke', 'author_id': 3058222, 'author_profile': 'https://Stackoverflow.com/users/3058222', 'pm_score': 0, 'selected': False, 'text': "<p>I've come up with this one, which has satisfied my requirements (I wanted my extension method to emulate as close as possible the return of the framework's TryParse, but without try{} catch{} blocks and without the compiler complaining about inferring a nullable type within the framework method)</p>\n\n<pre><code>private static bool TryParseNullableInt(this string s, out int? result)\n{\n    int i;\n    result = int.TryParse(s, out i) ? (int?)i : null;\n    return result != null;\n}\n</code></pre>\n"}, {'answer_id': 33022412, 'author': 'Crivelli', 'author_id': 1549600, 'author_profile': 'https://Stackoverflow.com/users/1549600', 'pm_score': 1, 'selected': False, 'text': '<pre><code>    public static void Main(string[] args)\n    {\n\n        var myString = "abc";\n\n        int? myInt = ParseOnlyInt(myString);\n        // null\n\n        myString = "1234";\n\n        myInt = ParseOnlyInt(myString);\n        // 1234\n    }\n    private static int? ParseOnlyInt(string s)\n    {\n        return int.TryParse(s, out var i) ? i : (int?)null;\n    }\n</code></pre>\n'}, {'answer_id': 33628246, 'author': 'lison', 'author_id': 1182712, 'author_profile': 'https://Stackoverflow.com/users/1182712', 'pm_score': 0, 'selected': False, 'text': '<p>I suggest code bellow. You may work with exception, when convert error occured.</p>\n\n<pre><code>public static class Utils {      \npublic static bool TryParse&lt;Tin, Tout&gt;(this Tin obj, Func&lt;Tin, Tout&gt; onConvert, Action&lt;Tout&gt; onFill, Action&lt;Exception&gt; onError) {\n  Tout value = default(Tout);\n  bool ret = true;\n  try {\n    value = onConvert(obj);\n  }\n  catch (Exception exc) {\n    onError(exc);\n    ret = false;\n  }\n  if (ret)\n    onFill(value);\n  return ret;\n}\n\npublic static bool TryParse(this string str, Action&lt;int?&gt; onFill, Action&lt;Exception&gt; onError) {\n  return Utils.TryParse(str\n    , s =&gt; string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)\n    , onFill\n    , onError);\n}\npublic static bool TryParse(this string str, Action&lt;int&gt; onFill, Action&lt;Exception&gt; onError) {\n  return Utils.TryParse(str\n    , s =&gt; int.Parse(s)\n    , onFill\n    , onError);\n}\n}\n</code></pre>\n\n<p>Use this extension method in code (fill int? Age property of a person class):</p>\n\n<pre><code>string ageStr = AgeTextBox.Text;\nUtils.TryParse(ageStr, i =&gt; person.Age = i, exc =&gt; { MessageBox.Show(exc.Message); });\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>AgeTextBox.Text.TryParse(i =&gt; person.Age = i, exc =&gt; { MessageBox.Show(exc.Message); });\n</code></pre>\n'}, {'answer_id': 49231363, 'author': 'Aleksandr Neizvestnyi', 'author_id': 4768299, 'author_profile': 'https://Stackoverflow.com/users/4768299', 'pm_score': 2, 'selected': False, 'text': '<p>I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:</p>\n\n<pre><code>public static int ParseInt(this string value, int defaultIntValue = 0)\n        {\n            return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;\n        }\n\npublic static int? ParseNullableInt(this string value)\n        {\n            if (string.IsNullOrEmpty(value))\n                return null;\n\n            return value.ParseInt();\n        }\n</code></pre>\n'}, {'answer_id': 52969952, 'author': 'SomeDeveloper', 'author_id': 9557852, 'author_profile': 'https://Stackoverflow.com/users/9557852', 'pm_score': 5, 'selected': False, 'text': '<h3>C# &gt;= 7.1</h3>\n<pre><code>var result = int.TryParse(foo, out var f) ? f : default;\n</code></pre>\n<p><sub>See <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version" rel="nofollow noreferrer">C# language versioning</a> to ascertain what language version your project supports</sub></p>\n'}, {'answer_id': 70716864, 'author': 'Jeremy Leff', 'author_id': 3348326, 'author_profile': 'https://Stackoverflow.com/users/3348326', 'pm_score': 1, 'selected': False, 'text': '<p>The cleaner way would be to write a separate function or extension method, but if you just want a one-liner:</p>\n<pre><code>string s;\nint? i = s == null ? (int?)null : int.Parse(s);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/45030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2975/']