Risho
Risho

Reputation: 2647

Ternary Operator Unexpected Result

Can someone comment on the issue I'm having. A ternary operator throws an error and the argument here is that if it evaluates to null then it should ignore the part after the colon. The Watch set up for this indicates an exception:

Int32.Parse(SQLDataReader["TrayId"].ToString())' threw an exception of Type 'System.FormatException

suggesting that it can't convert a null to a string. Is this how it works?

ShipmentId = SQLDataReader["ShipmentId"] == DBNull.Value ? 0 : Int32.Parse(SQLDataReader["ShipmentId"].ToString()),

Upvotes: 1

Views: 290

Answers (2)

gunr2171
gunr2171

Reputation: 17510

The column ShipmentId is an integer, but it is also nullable, which means that the c# type is int?.

The error boils down to this code:

Int32.Parse((string)null)

The parsing gives up because you can't turn null into an int.

To fix this, use TryParse.

int ShipmentId = 0;
int.TryParse(SQLDataReader["ShipmentId"].ToString(), out ShipmentId);

This will cover if the value is null, or if for some strange reason the value can't actually be converted to an int (like "asdf121343fds").

Upvotes: 3

Nick Raverty
Nick Raverty

Reputation: 431

It's recommended that for comparisons with DBNull, you use the DBNull.Value.Equals method, as described on this page: http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

ShipmentId = DBNull.Value.Equals(SQLDataReader["ShipmentId"]) ? 0 : Int32.Parse(SQLDataReader["ShipmentId"].ToString());

Upvotes: 2

Related Questions