C# does not work well with boxed numerical values. Unlike Visual Basic, the basic numeric comparison operators such as == do not work with boxed types even when both values are the same type.
Variable | Type | Value |
---|---|---|
a | int | 0 |
b | decimal | 0.0 |
c | decimal | 0.0 |
boxA | boxed int | 0 |
boxB | boxed decimal | 0.0 |
boxC | boxed decimal | 0.0 |
dynA | dynamic holding an int | 0 |
dynB | dynamic holding a decimal | 0.0 |
dynC | dynamic holding a decimal | 0.0 |
Comparison | C# | VB |
---|---|---|
a==b | true | true |
b==a | true | true |
b==c | true | true |
a.Equals(b) | false | <-- |
b.Equals(c) | true | <-- |
boxA == boxB | false | true |
boxB == boxA | false | true |
boxB == boxC | false | true |
boxA.Equals(boxB) | false | <-- |
boxB.Equals(boxC) | true | <-- |
dynA == dynB | true | n/a |
dynB == dynA | true | n/a |
dynB == dynC | true | n/a |
As you can see, using C# 3 and earlier even two boxed decimals with the same value will evaluate as being unequal. This occurs even when the Equals method on the Decimal class would otherwise return true.
Fortunately with C# 4 you can avoid these problems. By first casting the boxed values as dynamic, you do get the correct results even when comparing different types.
Console.WriteLine((dynamic)boxA == (dynamic)boxB);
Community comments
Re: Making 0 Equal 0 in C#
by Stefan Wenig,
Re: Making 0 Equal 0 in C#
by Francois Ward,
Re: Making 0 Equal 0 in C#
by Stefan Wenig,
Re: Making 0 Equal 0 in C#
by Stefan Wenig,
Your message is awaiting moderation. Thank you for participating in the discussion.
I like the phrase "does not work well". C# has well-defined rules that avoid guesswork. Not just for the compiler, but also for the human reader. Trying to be too smart would make other (more likely cases) harder to read. VB is better in this respect only if you do trial-and-error coding.
To compare boxed values of the same type, use the static method Object.Equals (a, b). This is much more explicit than using "dynamic".
Comparing boxed integers to boxed decimals smells bad in any case. If you really need it, being a bit more explicit about it won't hurt.
Re: Making 0 Equal 0 in C#
by Francois Ward,
Your message is awaiting moderation. Thank you for participating in the discussion.
I agree. This was all designed purposely. It was the design we wanted. C# was a very very "static" language, where (most) everything had to be explicit. If for a particular project, I didn't want these behaviors, I would use something else (like VB!).
Now I feel we're losing an option instead of gaining some.
Re: Making 0 Equal 0 in C#
by Stefan Wenig,
Your message is awaiting moderation. Thank you for participating in the discussion.
What are we losing? "dynamic" is opt-in, and it consistently behaves as you would expect a dynamic language to. Don't want it, use "object".