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]);
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]);
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'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]);
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]);
}