5

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?

0

2 Answers 2

20

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?);
Sign up to request clarification or add additional context in comments.

Comments

5

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;
}

3 Comments

This won't compile.
@Lee realised a second too late that tryParse needs an int
"fixed" it. man this looks ugly though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.