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);
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
YaakovHatam
  • 2,314
  • 2
  • 22
  • 40

5 Answers5

7

Try this instead :

int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);
Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
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);
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
2

My I suggest the following ?

int value;
int? myInt = ( int.TryParse(myTextBox.Text, out value ) ) ? value : default(int?);
Mohnkuchenzentrale
  • 5,745
  • 4
  • 30
  • 41
  • It also handles the case that the string cannot be converted to a int, like malformed strings or overflow – jefissu Apr 19 '22 at 11:28
0
int? myInt=myTextBox.Text == "" ? (int?)null : 
    Convert.ToInt32(myTextBox.Text);
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
  • While this _may_ technically answer the question your answer would be significantly improved if you also state _why_ it does. – Ben Nov 11 '12 at 10:52
0
int number =!string.IsNullOrEmpty(temp) ? Convert.ToInt32(temp) : (int?) null;
Tushar
  • 85,780
  • 21
  • 159
  • 179
vijay joshi
  • 38
  • 1
  • 10