I know I can do this:
Int32 tempInt;
Int32? exitNum;
if (Int32.TryParse(fields[13], out tempInt))
exitNum = tempInt;
else
exitNum = null;
But why can’t I do this?
Int32 tempInt;
Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? tempInt : null;
Is there a way to assign a value to a nullable using the conditional operator?
One side of the conditional operator must be convertible to the type of the other side.
In your case, you have an
inton one side, andnull(a type-less expression) on the other side. Since neither side is directly compatible with the other side, it doesn’t work.You need to make sure that at least one side is an
int?, either by casting, or by writingnew int?().Write
Int32.TryParse(fields[13], out tempInt) ? tempInt : new int?()