Solved

Question about boxing in C#

Posted on 2014-07-30
9
248 Views
Last Modified: 2014-07-30
If you box a value-type variable, do you delete that variable from the stack? For example, suppose you declare an Integer variable named myInteger. This puts myInteger on the stack. If you box myInteger, you create a reference-type version of myInteger in the heap. In doing so, have you created two copies of myInteger as shown below?

1st Copy: value-type copy of myInteger on the stack
2nd Copy:  reference-type copy of myInteger in the heap

Or does the original myInteger on the stack get deleted automatically when you box it?
0
Comment
Question by:MBarongan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 40230111
You end up with two different copies of the value type. The two types are NOT kept in sync with each other. So what you do to one does NOT happen to the other.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40230342
Yes, when boxing a value type it is allocated on the heap, and the value is deleted from the stack.
And vice versa.

However you have an object address on the stack. See the drawing in the link below.

http://www.dotnet-tricks.com/Tutorial/csharp/HL1W121013-Understanding-Boxing-and-Unboxing-in-C
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
ID: 40230459
Yes, when boxing a value type it is allocated on the heap, and the value is deleted from the stack.
I don't believe that is correct. Take for example:

public void Example()
{
    int x = 1;
    object y = x;
}

Open in new window


If the 2nd assignment caused a deletion from the stack, then that would mean that x is no longer valid after the 2nd assignment. As FernandoSoto mentioned, you end up with two copies: one on the stack and one on the heap.

The CLR via C#, 4th ed. is a good book to pick up to understand the inner workings of the CLR.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 63

Accepted Solution

by:
Fernando Soto earned 300 total points
ID: 40230475
Hi MBarongan;

Here is a console application showing that the boxed and the value type it was created from are independent and that the value type still exist.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            // Value type that lives on the Stack
            int myInteger = 150;

            // Create an object that will hold the Boxed Value.
            // This value lives on the Heap
            TestBoxing tBoxing = new TestBoxing();
            // Box the myInteger into the object TestBoxing.
            tBoxing.BoxedInt = myInteger;

            Console.WriteLine("The myInteger lives on the stack : " + myInteger);
            Console.WriteLine("The boxed on the heap : " + tBoxing.ToString());

            // Now lets change the value on the heap
            tBoxing.BoxedInt = 50;

            Console.WriteLine("\nThe myInteger value has not changed on the stack : " + myInteger);
            Console.WriteLine("The boxed on the heap has changeed : " + tBoxing.ToString());

            // Now let change the value on the stack
            myInteger = 75;

            Console.WriteLine("\nThe myInteger value has changed on the stack : " + myInteger);
            Console.WriteLine("The boxed on the heap has NOT changed : " + tBoxing.ToString());

            // Unboxing the value in tBoxing
            int tUnboxed = tBoxing.BoxedInt;

            // Current Values
            Console.WriteLine("\nThe myInteger current value on stack : " + myInteger);
            Console.WriteLine("The boxed on the heap current value : " + tBoxing.ToString());
            Console.WriteLine("The unboxed current value : " + tBoxing.ToString());


            Console.ReadLine();
        }
    }

    public class TestBoxing
    {
        public int BoxedInt { get; set; }

        public override string ToString()
        {
            return BoxedInt.ToString();
        }
    }
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40230480
@Fernando Soto

Line 20 is not a boxing operation, nor is line 38 an unboxing operation.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40230512
2 kaufmed

Of course you are correct with your code - there are two values: one value type and one object. Therefore one is on a heap one is on a stack.
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 40230515
Tanks Kaufmed, I stand corrected. Here is the information directly from Microsoft and supports my initial post.

Boxing and Unboxing (C# Programming Guide)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40230554
It may be worth mentioning that nothing on the stack gets deleted until it goes out of scope--i.e. it's parent stack frame is popped off the stack. When talking about reference types, only the pointer is popped off the stack, not the data the pointer points to.

You might find the articles of Eric Lippert, a former developer on the C# compiler team, interesting to read:

http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx
http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx

Those three don't really discuss boxing, but they do try to clear up confusion about value types and references types in terms of storage.
0
 

Author Closing Comment

by:MBarongan
ID: 40230822
Thank you everyone for your input. I understand it now.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question