c# - Box and UnBox what does it means? -


possible duplicates:
why need boxing , unboxing in c#?
what boxing , unboxing , trade offs?

in c# doe sit means: "box , unbox"?

here extract msdn founded text.

but convenience comes @ cost. reference or value type added arraylist implicitly upcast object. if items value types, must boxed when added list, , unboxed when retrieved. both casting , boxing , unboxing operations decrease performance; effect of boxing , unboxing can significant in scenarios must iterate on large collections.

thanks!

here more detailed explanation looks @ internal of common language runtime.

first, let's make difference between value types , reference types:

  • a value type held on stack , copy of passed called methods
  • a reference value held in managed heap , stack holds pointer (reference) location. location, , not object, passed called methods

if don't know stack (don't offended), it's memory area holds local variables in method , addresses of caller functions used return instruction (just brief , provide general answer). when call method, sufficient area on stack statically allocated it, stack allocation called static allocation.

the heap, instead, memory area separated stack, property of running process, in allocation must first demanded operating system, , that's why it's called dynamic allocation (if don't run in if statement, example, memory may not allocated process, instead stack allocated).

just make final example on heap , stack: in languages such c++, declaring int[100] a; statically allocates 100*8 bytes on stack (64-bit system assumed), while int* = new int[100]; declares 8 bytes (on 64-bit systems) area on stack , requests 800 more bytes on heap, if , available.

now let's talk c#:

boxing

since int value type, , allocated on stack, when cast object or other reference type (actually there no other reference type int can inherit, it's general rule) value must become reference type. new area on heap allocated, object boxed inside , stack holds pointer it.

unboxing

just opposite: when have reference type, such object, , want cast value type, such int, new value must held on stack, clr goes heap, un-boxes value , copies stack.

in other words

remember int[] , int* examples? simply, when have int in c#, runtime expects stack location hold value instead when have object, expects real value in heap location pointed stack.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -