How can I use int.TryParse
with nullable int?
I am trying to do something like the following, which doesn't compile, obviously.
int? nr1 = int.TryParse(str1, out nr1) ? nr1 : null;
What is the correct way to achieve it?
Because the out
has to be int
you need something like:
int temp;
int? nr1 = int.TryParse(str1, out temp) ? temp : default(int?);
Note that I also use default(int?)
instead of null
because the conditional typing won't work otherwise. ? (int?)temp : null
or ? temp : (int?)null
would also solve that.
As of C#7 (VS Studio 2017) you can inline the declaration of temp
int? nr1 = int.TryParse(str1, out int temp) ? temp : default(int?);
int.tryParse
will change the referenced out
variable, and return a boolean
, which is true
if the passed argument could be parsed as an integer.
You're after something like this :
int? int1;
int tempVal;
if (!int.TryParse(str1, out tempVal))
{
int1 = null;
}
else
{
int1 = tempVal;
}