Solved

Question about boxing in C#

Posted on 2014-07-30
9
228 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
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 62

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 29

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
 
LVL 62

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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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 29

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 62

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

910 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

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now