[.net] boxing!?

Started by
5 comments, last by Daniel Miller 18 years, 10 months ago
I don't understand why this outputs "6":

SortedList sl = new SortedList();

sl.Add(2, 5);

sl[2] = (int)sl[2]+ 1;
 
Console.WriteLine(sl[2]);

I thought sl[2] would return a boxed copy of the number there, but itappears that it returns an actual reference. What is happenning?
Advertisement
Well, sl[2] is initially 5 because of your Add() call, so sl[2]+1 is 6, and you store that back in sl[2] and print it out.

Yes, but I thought that when you box and unbox you are only making copies.

Maybe this is what is happening?:

When 5 is Added to the list, it is added onto the heap "in a box". The indexer returns a reference to that box, which is then changed.

Is that right?
You're overwriting 5 with 6. The fact that the value 6 is wrapped in an object before it's put in the SortedList shouldn't be a source of confusion for you - what are you expecting the value to be and why?
I thought it should be 5:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfboxingconversionpg.asp

Edit: I don't know how to link. :(

That article shows the boxed value being seperate from the unboxed value.
For links, use the same code as plain HTML:
{a href="url..."}text for the link{/a}
(replace { with <).

For your question, I think that you don't realize that the assignment operator overwrites what's in sl[2]. Here's the details:

1. sl.Add(2, 5) adds a boxed 5 in s1;

2. sl[2] returns the boxed 5;
3. (int) unbox the 5;
4. + 1 returns the value 6;
5. the = assignment boxes the 6, and stores the boxed 6 in sl[2];

6. sl[2] returns the boxed 6;
7. WriteLine prints it on the console.

I hope things are more clear now.

Best,
jods
Yep, sl[2] returns the boxed value which is already being stored, which is why the changes stay. Thanks for clarifying. [grin]

This topic is closed to new replies.

Advertisement