c# short if statement not working with int? (int=null)
Posted
by
kobe
on Stack Overflow
See other posts from Stack Overflow
or by kobe
Published on 2012-11-11T10:25:04Z
Indexed on
2012/11/11
11:00 UTC
Read the original article
Hit count: 238
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);
© Stack Overflow or respective owner