-1

I am trying to understand whats happening and why it doesnt work. I was trying to convert "34" to the int 34. I wish to know why there is a difference (and why my version didnt work): My version:

var cell = GetSpecificString();
return (cell == "") ? null : int.Parse(cell);

SO version:

var cell = GetSpecificString();
if (int.TryParse(cell, out int i)) return i;
return null;

Any tips would be greatly appreciated, as I want to know whats happening here.

Does not work implies here that the Intellisense is complaining because there is no conversion between '' and 'int'. But I want to return a nullable int, so this seems weird to me.

WiseStrawberry
  • 317
  • 1
  • 4
  • 14

2 Answers2

2

The first version doesn't work because the conditional operator doesn't allow it whereas the second approach uses an if. The rules for the conditional operator are stricter. Both types must be compatible but null and int are not. You could achieve it by using:

return (cell == "") ? (int?)null : int.Parse(cell);

However, i'd really use int.TryParse since an empty string is not the only invalid value:

return int.TryParse(cell, out int parsedValue) ? parsedValue : new int?();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

There is already good explanation on stack overflow for this problem: For complete explanation refer Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>

The spec (§7.14) says that for conditional expression b ? x : y, there are three possibilities, either x and y both have a type and certain good conditions are met, only one of x and y has a type and certain good conditions are met, or a compile-time error occurs.

If only one of x and y has a type, and both x and y are implicitly convertible to that type, then that is the type of the conditional expression.