Solved

Question about boxing in C#

Posted on 2014-07-30
9
252 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

717 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