Jump to content
  • Advertisement
Sign in to follow this  
Daniel Miller

[.net] boxing!?

This topic is 4873 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!