Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Making 0 Equal 0 in C#

Making 0 Equal 0 in C#

Leia em Português


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);

Rate this Article