2

I'm trying single line if statement as follow and I'm getting error justifiably.How should i do it?

int? n;
n = (reader[0] == null)? null : Convert.ToInt32(reader[0]);
Goran Zooferic
  • 371
  • 8
  • 23

4 Answers4

8

Explicitly cast to int? like:

n = (reader[0] == null)? null :(int?) Convert.ToInt32(reader[0]);

Or:

n = (reader[0] == null) ? (int?) null : Convert.ToInt32(reader[0]);
Habib
  • 219,104
  • 29
  • 407
  • 436
0

Do you really need an if statement?

n = (int?) reader[0];
jmalm
  • 11
  • 1
0

Habib's answer is correct. However, I sometimes find the following convention easier to read:

int? n = null;
if (reader[0] != null)
    n = Convert.ToInt32(reader[0]);
Douglas
  • 53,759
  • 13
  • 140
  • 188
0

I'd avoid trying to do too many things in one line of code.

It's less maintainable, it's less readable and it compiles down to the same MSIL anyway.

Something like this is much more readable:

int? number = null;

if (reader[0] != null)
{
    number = Convert.ToInt32(reader[0]);
}
Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69