1

I have this property:

int? firstClientID;

Why does this

firstClientID = dataRow.IsFirstClientIDNull() 
                    ? null 
                    : (int.TryParse(dataRow.FirstClientID, out tempInt) 
                        ? tempInt 
                        : 0);

not compile because

type of conditional statement cannot be determined since there is no implicit conversion between null and int

and does

if (dataRow.IsFirstClientIDNull())
    firstClientID = null;
else if (int.TryParse(dataRow.FirstClientID, out tempInt))
    firstClientID = tempInt;
else
    firstClientID = 0;

work? They seem to do the same thing.

user2609980
  • 10,264
  • 15
  • 74
  • 143

1 Answers1

1

From MSDN

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

i.e. You will need to ensure both legs of the conditional operator return the same type (i.e. cast through Nullable<int>).

firstClientID = dataRow.IsFirstClientIDNull() 
                ? (int?)null
                : (int.TryParse(dataRow.FirstClientID, out tempInt) 
                    ? tempInt 
                    : 0);

(The conditional operator is not really the same as an if / then else branch, as the conditional operator must return data of the same type, whereas if can do anything in each leg of the branches, with no constraints on type compatability)

StuartLC
  • 104,537
  • 17
  • 209
  • 285