c# short if statement not working with int? (int=null)
Asked Answered
K

5

7

I am trying to shorten my code by using short-if:

int? myInt=myTextBox.Text == "" ? null : 
    Convert.ToInt32(myTextBox.Text);

But I'm getting the following error: Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'int'

The following works:

int? myInt;
if (myTextBox.Text == "") //if no text in the box
   myInt=null;
else
   myInt=Convert.ToInt32(myTextBox.Text);

And if I replace the 'null' in integer (say '4') it also works:

int? myInt=myTextBox.Text == "" ? 4: 
    Convert.ToInt32(myTextBox.Text);
Kalgan answered 11/11, 2012 at 10:25 Comment(1)
This is not a short if, but a ternary operator.Orchid
I
7

Try this instead :

int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);
Intricacy answered 11/11, 2012 at 10:27 Comment(1)
You guys all don't give much about int.TryParse hm :) ?Stamey
M
4

What we need is to let the compiler know, that both parts of the if expression (if and else) are the same. And that's why C# contains the word default:

int? myInt=myTextBox.Text == "" 
   ? default(int?)
   : Convert.ToInt32(myTextBox.Text);
Mixture answered 11/11, 2012 at 10:34 Comment(0)
S
2

My I suggest the following ?

int value;
int? myInt = ( int.TryParse(myTextBox.Text, out value ) ) ? value : default(int?);
Stamey answered 11/11, 2012 at 10:33 Comment(1)
It also handles the case that the string cannot be converted to a int, like malformed strings or overflowAphasic
P
0
int? myInt=myTextBox.Text == "" ? (int?)null : 
    Convert.ToInt32(myTextBox.Text);
Paterson answered 11/11, 2012 at 10:30 Comment(1)
While this may technically answer the question your answer would be significantly improved if you also state why it does.Switzerland
N
0
int number =!string.IsNullOrEmpty(temp) ? Convert.ToInt32(temp) : (int?) null;
Nolannolana answered 27/12, 2016 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.