API's that Suck

June 1, 2009

Should 0 equal 0.0?

Filed under: Uncategorized — Grauenwolf @ 8:05 pm

Should the integer 0 be equal to the decimal 0.0?

C# says maybe:

int a = (int)0;
decimal b = (decimal)0.0;
Console.WriteLine(a == b); //true
Console.WriteLine(b == a); //true

object boxA = (int)0;
object boxB = (decimal)0.0;
Console.WriteLine(boxA == boxB); //false
Console.WriteLine(boxB == boxA); //false

By contrast, Visual Basic says yes.

Dim a As Integer = CInt(0)
Dim b As Decimal = CDec(0.0)
Console.WriteLine(a = b) 'true
Console.WriteLine(b = a) 'true

Dim boxA As Object = CInt(0)
Dim boxB As Object = CDec(0.0)
Console.WriteLine(boxA = boxB) 'true
Console.WriteLine(boxB = boxA) 'true


The VB code looks like this in C#

Console.WriteLine(RuntimeHelpers.GetObjectValue(Operators.CompareObjectEqual(boxA, boxB, false)));

C# code looks like this in VB

Console.WriteLine((boxA Is boxB))
As you can see, C# assumes that you want == to mean reference equality when dealing with variables of type Object. Meanwhile, VB is using helper functions because it doesn’t automatically trust the Object.Equals(Object) method to be correct.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: