Solution to the “no implicit conversion…” using the Conditional Operator ? :

<![CDATA[

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 ? :

]]>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s