I'm engaged in educating myself about C# via Troelsen's Pro C# book.
I'm familiar with the stack and heap and how C# stores these sorts of things. In C++, whenever we use new
we receive a pointer to something on the heap. However, in C# the behavior of new
seems different to me:
new
seems to merely call the int default constructor yet the value of such an int would still be stored on the stackI understand that all objects/structs and such are stored on the heap, regardless of whether or not new
is used.
So my question is: how can I instantiate an int
on the heap? (And does this have something to do with 'boxing'?)
In C the character values are also stored as integers. In the following code, we shall put 270 into a character type data. So the binary equivalent of 270 is 100001110, but takes only first 8-bits from right. So the result will be (00001110), that is 14.
C requires int be at least as many bits as char . Therefore, int can store the same values as char (allowing for signed/unsigned differences). In most cases, int is a lot larger than char .
You can box any value type to System.Object
type so it will be stored on the managed heap:
int number = 1;
object locatedOnTheHeap = number;
An other question is why you need this.
This is a classic example from the must-know MSDN paper: Boxing and Unboxing (C# Programming Guide)
When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
.
I understand that all objects/structs and such are stored on the heap
BTW, IIRC sometimes JIT optimizes code so value type objects like of type like int
are stored in the CPU registers rather than stack.
I do not know why you would want to do this, however, in theory you could indeed box your value. You would do this by boxing the int into an object (which is a reference type and will be placed on the stack:
object IAmARefSoIWillBeOnHeap = (object)1;
*As sll stated, you do not need the (object)
as it will be an implicit cast. This is here merely for academic reasons, to show what is happening.
Here is a good article about reference versus value types, which is the difference of the heap versus the stack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With