Solved

Question about boxing in C#

Posted on 2014-07-30
9
216 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
Comment Utility
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
Comment Utility
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 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
@Fernando Soto

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

Expert Comment

by:anarki_jimbel
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
Thank you everyone for your input. I understand it now.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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 is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This video discusses moving either the default database or any database to a new volume.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

772 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

10 Experts available now in Live!

Get 1:1 Help Now