Solved

Question about boxing in C#

Posted on 2014-07-30
9
243 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 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 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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
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…

808 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