Q about conditional

  • Thread starter Thread starter AP
  • Start date Start date
A

AP

Why do I get a conversion error with this line of code? (Type of conditional
expression can't be determined because there is no implicit conversion
between 'int' and 'System.DBNull')
object o = (1+2 ==3) ? 3 : DBNull.Value;

when

object o;

if (1+2==3) {

o = 3;

else {

o = DBNull.Value;

}

works...shouldn't they be doing the same thing??
 
You have to write it
object o = (1+2 == 3) ? (object)3 : DbNull.Value;

Compiler will bark if you have a conditional like :

T1 t1 = test ? t2 : t3 // t2 of type T2, t3 of type T3

and if neither T2 is assignable to T3, nor T3 assignable to T2 (even though
they may be both assignable to T1).

So, by casting t2 to object, you get T3 assignable to T2

Java works the same way.

Bruno.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top