How to parse a string into a nullable int
Solution 1:
int.TryParse
is probably a tad easier:
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
Edit @Glenn int.TryParse
is "built into the framework". It and int.Parse
are the way to parse strings to ints.
Solution 2:
You can do this in one line, using the conditional operator and the fact that you can cast null
to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse
):
Pre C#7:
int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;
With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.
int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;
Solution 3:
[Updated to use modern C# as per @sblom's suggestion]
I had this problem and I ended up with this (after all, an if
and 2 return
s is soo long-winded!):
int? ToNullableInt (string val)
=> int.TryParse (val, out var i) ? (int?) i : null;
On a more serious note, try not to mix int
, which is a C# keyword, with Int32
, which is a .NET Framework BCL type - although it works, it just makes code look messy.
Solution 4:
C# >= 7.1
var result = int.TryParse(foo, out var f) ? f : default;
See C# language versioning to ascertain what language version your project supports