473,322 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Boxing

SK
What is the real use of boxing and unboxing
in what situations will it be used.
Since all types are utlmately dereived from object..what
is the need for boxing and unboxing.....help
Jul 21 '05 #1
13 2996
SK <an*******@discussions.microsoft.com> wrote:
What is the real use of boxing and unboxing
in what situations will it be used.
Since all types are utlmately dereived from object..what
is the need for boxing and unboxing.....help


Boxing and unboxing makes it much easier to deal with value types in
situations where what is expected is a reference type. For instance, it
is boxing which allows us to add an int to an ArrayList, or set the
value in a DataRow to a float, etc.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #2
"SK" <an*******@discussions.microsoft.com> wrote in
news:9d****************************@phx.gbl...
What is the real use of boxing and unboxing
in what situations will it be used.
Since all types are utlmately dereived from object..what
is the need for boxing and unboxing.....help


Of course all value types are derived from object, that's what makes boxing
possible from a language perspective. But (without boxing) value types
always live on the stack and reference types always live on the heap: If you
want to get a value type on the heap, you need a "reference type box" around
it, that's why it's called boxing.

Niki
Jul 21 '05 #3
Niki Estner <ni*********@cube.net> wrote:
"SK" <an*******@discussions.microsoft.com> wrote in
news:9d****************************@phx.gbl...
What is the real use of boxing and unboxing
in what situations will it be used.
Since all types are utlmately dereived from object..what
is the need for boxing and unboxing.....help
Of course all value types are derived from object, that's what makes
boxing possible from a language perspective.


There's actually some extra complexity there. The value type itself
*doesn't* derive from System.Object. The boxed value type derived from
System.Object (via System.ValueType). The two types have the same name.
It's all a bit odd - see section 8.2.4 of the CIL spec for more
information.

However, it's up to the language itself to define the boxing
conversions it wants to implement.
But (without boxing) value types
always live on the stack and reference types always live on the heap


Not true. For instance:

public class Test
{
int i = 5;

static void Main()
{
Test t = new Test();
}
}

That has created a value type within the Test type. The object itself
(containing the value type value) is on the heap.

See http://www.pobox.com/~skeet/csharp/memory.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #4
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in
news:MP***********************@msnews.microsoft.co m...
...
Of course all value types are derived from object, that's what makes
boxing possible from a language perspective.


There's actually some extra complexity there. The value type itself
*doesn't* derive from System.Object. The boxed value type derived from
System.Object (via System.ValueType). The two types have the same name.
It's all a bit odd - see section 8.2.4 of the CIL spec for more
information.


I should have mentioned that I was talking about *high-level* language
perspective, like C# or VB.net.
But (without boxing) value types
always live on the stack and reference types always live on the heap


Not true. For instance:

public class Test
{
int i = 5;

static void Main()
{
Test t = new Test();
}
}

That has created a value type within the Test type. The object itself
(containing the value type value) is on the heap.


:-)
I assume you know what I meant.

Niki
Jul 21 '05 #5
Niki Estner <ni*********@cube.net> wrote:
But (without boxing) value types
always live on the stack and reference types always live on the heap
Not true. For instance:


<snip>
I assume you know what I meant.


Yup, but others don't necessarily. The reason I wrote the memory page
in the first place is that people say "Value types are always stored on
the stack" and then people reading that get (understandably, IMO)
confused as to where value type members of reference types actually
*do* live.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #6
Yes all types are derived from Object, but types that derive from
System.ValueType (aka value type) objects have different memory
semantics. Normal(reference) types in .Net are allocated memory on the
managed heap, whereas value types are allocated menory on the stack.
That is why there needs to be boxing, when a reference type object is
expected and we pass a value type, the runtime automatically allocates
memory on the heap and copies the value of the value type into the new
object.

Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph

SK wrote:
What is the real use of boxing and unboxing
in what situations will it be used.
Since all types are utlmately dereived from object..what
is the need for boxing and unboxing.....help

Jul 21 '05 #7
Sijin Joseph <si***************@hotmail.com> wrote:
Yes all types are derived from Object, but types that derive from
System.ValueType (aka value type) objects have different memory
semantics. Normal(reference) types in .Net are allocated memory on the
managed heap, whereas value types are allocated menory on the stack.


That's an oversimplification which isn't really true.

See http://www.pobox.com/~skeet/csharp/memory.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #8
That's a great article Jon! I sure did miss the part where Value types
are fields of Reference types. But one question comes to mind, in this
case will boxing occur? (since the value is already on the heap)
Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
Jon Skeet [C# MVP] wrote:
Sijin Joseph <si***************@hotmail.com> wrote:
Yes all types are derived from Object, but types that derive from
System.ValueType (aka value type) objects have different memory
semantics. Normal(reference) types in .Net are allocated memory on the
managed heap, whereas value types are allocated menory on the stack.

That's an oversimplification which isn't really true.

See http://www.pobox.com/~skeet/csharp/memory.html

Jul 21 '05 #9
Sijin Joseph <si***************@hotmail.com> wrote:
That's a great article Jon! I sure did miss the part where Value types
are fields of Reference types. But one question comes to mind, in this
case will boxing occur? (since the value is already on the heap)


No. Boxing occurs when you need to view a value type as a reference
type - it's sort of when a value type value needs to be on the heap "on
its own" rather than as part of another object.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #10
Hi Jon,

Although i am sure that internally no boxing takes place in this case,
but surprisingly the compiler does generate the box instruction.

I compiles this code

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Test t = new Test();
ArrayList al = new ArrayList();
al.Add(t.a);
}
}

public class Test
{
public int a = 5;
}

and i got this IL

..method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() =
( 01 00 00 00 )
// Code size 31 (0x1f)
.maxstack 2
.locals init ([0] class ConsoleApplication1.Test t,
[1] class [mscorlib]System.Collections.ArrayList al)
IL_0000: newobj instance void ConsoleApplication1.Test::.ctor()
IL_0005: stloc.0
IL_0006: newobj instance void
[mscorlib]System.Collections.ArrayList::.ctor()
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldloc.0
IL_000e: ldfld int32 ConsoleApplication1.Test::a
IL_0013: box [mscorlib]System.Int32 // Box call is generated
IL_0018: callvirt instance int32
[mscorlib]System.Collections.ArrayList::Add(object)
IL_001d: pop
IL_001e: ret
} // end of method Class1::Main

Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
Jon Skeet [C# MVP] wrote:
Sijin Joseph <si***************@hotmail.com> wrote:
That's a great article Jon! I sure did miss the part where Value types
are fields of Reference types. But one question comes to mind, in this
case will boxing occur? (since the value is already on the heap)

No. Boxing occurs when you need to view a value type as a reference
type - it's sort of when a value type value needs to be on the heap "on
its own" rather than as part of another object.

Jul 21 '05 #11
Sijin Joseph <si***************@hotmail.com> wrote:
Although i am sure that internally no boxing takes place in this case,
but surprisingly the compiler does generate the box instruction.

I compiles this code

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Test t = new Test();
ArrayList al = new ArrayList();
al.Add(t.a);
}
}

public class Test
{
public int a = 5;
}


There's nothing surprising about a box happening here - adding an int
to an ArrayList will always box, as it's got to store it in an object
for the ArrayList to work. (Note that ArrayList.Add takes object, not
int.)

You'll see the same thing if you just try

al.Add(5);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #12
Well it's surprising because 't.a' is already on the heap, since it is
part of a reference type. What would be intresting is to see if the
boxing is actually taking place, although the box instruction is being
generated, is the JITer is actually creating a new object on the heap to
store the value. It would be intresting to look at the rotor sources to
check the same.

Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
Jon Skeet [C# MVP] wrote:
Sijin Joseph <si***************@hotmail.com> wrote:
Although i am sure that internally no boxing takes place in this case,
but surprisingly the compiler does generate the box instruction.

I compiles this code

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Test t = new Test();
ArrayList al = new ArrayList();
al.Add(t.a);
}
}

public class Test
{
public int a = 5;
}

There's nothing surprising about a box happening here - adding an int
to an ArrayList will always box, as it's got to store it in an object
for the ArrayList to work. (Note that ArrayList.Add takes object, not
int.)

You'll see the same thing if you just try

al.Add(5);

Jul 21 '05 #13
Sijin Joseph <si***************@hotmail.com> wrote:
Well it's surprising because 't.a' is already on the heap, since it is
part of a reference type.
Yes, but it's not a separate object. Note that al.Add isn't taking
"t.a" as the parameter - it's taking the *value* of t.a as the
parameter.
What would be intresting is to see if the
boxing is actually taking place, although the box instruction is being
generated, is the JITer is actually creating a new object on the heap to
store the value. It would be intresting to look at the rotor sources to
check the same.


The CLR *must* create a new object on the heap. Your instance of Test
is eligible for garbage collection, which means there must be another
copy of the data somewhere, and it must be on the heap.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Lora Connors | last post by:
What is Boxing & UnBoxing in .NET?
43
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's...
1
by: Tom | last post by:
Couple of questions relating to boxing. Firstly, I already know that boxing is the processing of temporarily copying a ValueType (e.g. struct, enum) to the heap so that the system can treat a...
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
4
by: Peter Olcott | last post by:
I want to be able to make my .NET applications run just as fast as unmanaged C++. From my currently somewhat limited understanding of the .NET framework and the C# language, it seems that...
14
by: dave.dolan | last post by:
Basically I'd like to implement the composite design pattern with leaves that are either of reference or value types, but even using generics I can't seem to avoid boxing (using ArrayList or...
94
by: Peter Olcott | last post by:
How can I create an ArrayList in the older version of .NET that does not require the expensive Boxing and UnBoxing operations? In my case it will be an ArrayList of structures of ordinal types. ...
19
by: ahjiang | last post by:
hi there,, what is the real advantage of boxing and unboxing operations in csharp? tried looking ard the internet but couldnt find any articles on it. appreciate any help
161
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.