Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you store an int or other "C# value types" on the heap (with C#)?

Tags:

c#

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:

  • when used with value types like an int, using new seems to merely call the int default constructor yet the value of such an int would still be stored on the stack

I 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'?)

like image 300
ybakos Avatar asked Mar 27 '12 16:03

ybakos


People also ask

How is an integer stored in C?

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.

Can I store int in char in C?

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 .


2 Answers

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.

like image 158
sll Avatar answered Oct 06 '22 01:10

sll


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

like image 45
Justin Pihony Avatar answered Oct 06 '22 01:10

Justin Pihony