1

Does anyone have an idea why this works:

if (_item.Created == DateTime.MinValue)
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", DBNull.Value));
}
else
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", _item.Created));
}

but not this:

ListSqlParam.Add(new SqlParameter("@TransactionCreated",((_item.Created == DateTime.MinValue) ? DBNull.Value : _item.Created)));
3
  • What doesnt work in the second case? Commented Dec 3, 2012 at 12:34
  • 1
    @ryadavilli - It will not compile. Commented Dec 3, 2012 at 12:34
  • DBNull.Value isn't the same type as _item.Created. Commented Dec 3, 2012 at 12:36

3 Answers 3

3

The reason is that the conditional operator is an expression of a specific type. This specific type is infered by the compiler based on the types of the expressions in the two branches of the operator.
In your code, this specific type can't be infered by the compiler because DBNull.Value and _item.Created are of different and unrelated types. You can't cast either one to the type of the other one.

To make it work, cast at least one branch to object:

(_item.Created == DateTime.MinValue) ? (object)DBNull.Value : _item.Created
Sign up to request clarification or add additional context in comments.

Comments

0

When using the conditional operator, both types returned by the different sides of the conditional (the true and the false branches) should be the same or be implicitly convertible to each other.

DBNull.Value and DateTime are not such values.

Comments

0

Use SqlDateTime instead :

_item.Created == DateTime.MinValue ? SqlDateTime.Null : new SqlDateTime(_item.Created)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.