Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 307
YaakovHatam Avatar asked Nov 11 '12 10:11

YaakovHatam


3 Answers

Try this instead :

int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);
like image 190
Kundan Singh Chouhan Avatar answered Oct 19 '22 11:10

Kundan Singh Chouhan


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);
like image 34
Radim Köhler Avatar answered Oct 19 '22 11:10

Radim Köhler


My I suggest the following ?

int value;
int? myInt = ( int.TryParse(myTextBox.Text, out value ) ) ? value : default(int?);
like image 20
KroaX Avatar answered Oct 19 '22 11:10

KroaX