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);
Try this instead :
int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);
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);
My I suggest the following ?
int value;
int? myInt = ( int.TryParse(myTextBox.Text, out value ) ) ? value : default(int?);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With