I stumbled across Part 6 of a Programming Job Interview Challenge on the Dev102 blog and thought, "hey, I know this!" I couldn't help responding.
So the question was, given this bit of code, what will the output be?
1: ArrayList a = new ArrayList();
2: ArrayList b = new ArrayList();
3:
4: a.Add(1);
5: b.Add(1);
6: a.Add(2);
7: b.Add(2.0);
8:
9: Console.WriteLine((a[0] == b[0]));
10: Console.WriteLine((a[1] == b[1]));
Ok, so I'll break the post here in case you want to work it out for yourself, but you should really go to the original post - not least because there are five other challenges there.
Anyway, the short answer is you'd get two "false"s. The reason? It's all to do with the way the information is stored, and how the equality operator works.
Usually, when you're writing code in C#, you don't have to think too much about how pieces of data are stored in memory. This is not one of those times. Because the primitive numbers are stored in an ArrayList, they are boxed into memory locations. If the code simply said "1 == 1" rather than "a[0] == b[0]", then you'd get a True, but because you're comparing one memory location with another, they're never going to be equal.
Now if you were to use the .Equals function, then you'd get a true result, at least for zeroth items of the ArrayLists (but not for the next one - 2 doesn't equal 2.0).
So, let that be the lesson - if your primitives are wrapped (or boxed), then use the Equals method rather than the equals operator (==).