Some Creativity

Weblog of Siddharth Uppal

Archive for June 6th, 2008

ArrayList item comparison

with one comment

What’ll be the output of the following piece of code (asked here)?


		ArrayList a = new ArrayList();
		ArrayList b = new ArrayList();

		a.Add(1);
		b.Add(1);
		a.Add(2);
		b.Add(2.0);

		Console.WriteLine(a[0] == b[0]);
		Console.WriteLine(a[1] == b[1]);

One might expect…

True
True

But what you’d actually get is…

False
False

…because of boxing.

a.Add(1) boxes the integer 1 into an object and stores it in a, while b.Add(1) boxes the integer 1 into a separate object and stores it in b. Since a[0] and b[0] are going to be different objects, the check is going to fail. Same logic applies when comparing a[1] and b[1].

However, it gets interesting. If you tried to do a similar thing in VB.NET, the output would be different.

So with a code like this…


		Dim a as new ArrayList()
		Dim b as new ArrayList()

		a.Add(1)
		b.Add(1)
		a.Add(2)
		b.Add(2.0)

		Console.WriteLine(a(0) = b(0))
		Console.WriteLine(a(1) = b(1))		

The output is going to be…

True
True

Surprised :) Well, VB.NET compiler translates the equality check (”=”) to a call to a helper function part of VB.NET runtime which would cast the left and right hand sides appropriately before comparison. In the first case, it would compare the two objects as integers, while in the second case it would compare the two objects as doubles after converting the integer on left hand side to a double.

That’s why we have generics - no surprises like these…

Written by Sid

June 6th, 2008 at 10:14 am

Posted in .NET, Tech/Hacks