Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.Int32 take 24 bytes?

Tags:

c#

.net

boxing

If an int takes 4 bytes, why does System.Int32 takes 24 bytes when boxing an integer into an object?

For example:

int i = 3;
object o = i;
like image 214
ILovePizza Avatar asked Aug 28 '26 14:08

ILovePizza


1 Answers

In C#/CLR reference types have some size overhead:

The layout of a managed object is pretty simple: a managed object contains instance data, a pointer to a meta-data (a.k.a. method table pointer) and a bag of internal information also known as an object header.

enter image description here

So when you box your int into the heap it will be stored as a reference type and will include all the extra info and then the memory will be aligned resulting in something like this:

Object Header (8 bytes)
Method Table Pointer (8 bytes)
Int (4 bytes)
padding (4 bytes, to align at 8 bytes)

Note that this is dependent on the bitness of the process (the breakdown above is for 64-bit case) and is actually runtime implementation detail (the previously linked article mentions at least one implementation that differs).

like image 198
Guru Stron Avatar answered Aug 30 '26 04:08

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!