Meeting the needs of your business from a distance

Odd Conditional Operator Scenario

by mark shiffer 23. September 2009 13:42

Okay, without cheating, what do you think the message box will display in the following code:

   1: bool convertToInt = true;
   2: decimal test = 5;
   3:  
   4: object result = convertToInt ? Convert.ToInt32(test) : test;
   5:  
   6: MessageBox.Show(result.GetType().ToString());

Three choices come to mind: System.Int32, System.Decimal and System.Object.

The result is actually System.Decimal. I ran into this little oddity recently in code and it sent me for a bit of a loop. Reading the C# language specification sheds some light on exactly what the conditional operator is doing though:

7.13 Conditional operator

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
•    If X and Y are the same type, then this is the type of the conditional expression.
•    Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
•    Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
•    Otherwise, no expression type can be determined, and a compile-time error occurs.

Since an implicit conversion from Int32 to Decimal exists, the compiler is choosing Decimal as the type for the expression.

Tags:

Programming | Issues

Comments

Add comment


(Will show your Gravatar icon)

  Country flag


  • Comment
  • Preview
Loading



Copyright © 2001-2012 MS Consulting, Inc. All Rights Reserved.