Body:
A co-worker was having a problem using the Conditional Operator ( ? : ). He could have easily used the standard if..else.. statement but he wanted to use the inline convenience of the conditional operator. This is normally not an issue; however, this can become a problem at times such as assigning values to a SQL Parameter or other generic data types.
I suggested he cast the conditional values to the object data type. Below is an example.
public void TestConditionOperator()
{
// Conditional Operator: ? :
bool isUsa = true;
SqlParameter param = new SqlParameter();
// Problem: 'System.DBNull' and 'string' (“USA“) are different object types.
param.Value = isUsa ? DBNull.Value : "USA";
// The above line of code generates the following error:
// Type of conditional expression can't be determined because there is no implicit
// conversion between 'System.DBNull' and 'string'
// Solution: Cast each object to an object data type.
param.Value = isUsa ? DBNull.Value as object: "USA" as object;
}
Published: 4/30/2004 12:00 AM
Title: Solution to the “no implicit conversion…” using the Conditional Operator ? :
That’s the solution I’m looking for. Thanks!