Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boxing and Unboxing [duplicate]

Tags:

c#

.net

clr

Possible Duplicate:
What is boxing and unboxing and what are the trade offs?

Ok I understand the basic concept of what happens when you box and unbox.

Box throws the value type (stack object) into a System.Object and stores it on the heap Unbox unpackages that object on the heap holding that value type and throws it back on the stack so it can be used.

Here is what I don't understand:

  1. Why would this need to be done...specific real-world examples

  2. Why is generics so efficient? They say because Generics doesn't need to unbox or box, ok..I don't get why...what's behind that in generics

  3. Why is generics better than lets say other types. Lets say for example other collections?

so all in all I don't understand this in application in the real world in terms of code and then going further how it makes generics better...why it doesn't have to do any of this in the first place when using Generics.

like image 763
PositiveGuy Avatar asked Dec 13 '22 18:12

PositiveGuy


2 Answers

  1. Boxing needs to be done whenever you want to hold an int in an object variable.
  2. A generic collection of ints contains an int[] instead of an object[].
  3. Putting an int into the object[] behind a non-generic collection requires you to box the int.
    Putting an int into the int[] behind a generic collection does not invlove any boxing.
like image 60
SLaks Avatar answered Dec 30 '22 09:12

SLaks


Firstly, the stack and heap are implementation details. a value type isnt defined by being on the stack. there is nothing to say that the concept of stack and heap will be used for all systems able to host the CLR: Link

That aside:

when a value type is boxed, the data in that value type is read, an object is created, and the data is copied to the new object. if you are boxing all the items in a collection, this is a lot of overhead.

if you have a collection of value types and are iterating over them, this will happen for each read, then the items are then unboxed (the reverse of the process) just to read a value!!

Generic collections are strongly typed to the type being stored in them, and therefore no boxing or unboxing needs to occur.

like image 32
TimC Avatar answered Dec 30 '22 10:12

TimC