2

I already watched a session from Mario Hewardt that mentions a class containing an integer property takes 16 bytes of space. I'd like to know how the size of a simple following class can result in 16?

[StructLayout(LayoutKind.Sequential)]
public class MyClass
{
    public int Age;
}

The problem is that the integer takes 4 bytes of space (right?) so where the heck those 12 other bytes come from? I've also used Marshal.SizeOf to get the class size which resulted in 4:

int n = Marshal.SizeOf(typeof(MyClass));
//n == 4

I've read this and it seems that the above class holds 8 bytes of internal data (what are these data anyway?), 4 byte for the int value, and 4 bytes of unused space. So if it takes 16 byte, why Marshal.SizeOf returns 4? and if it takes 4, where those 8 bytes are gone? I'm truly confused.

Community
  • 1
  • 1
Joe Bank
  • 653
  • 7
  • 20

2 Answers2

2

Marshal.SizeOf(Type) returns the size of the equivalent unmanaged type, i.e. how many bytes would the equivalent unmanaged type (e.g. a C++ class) take if it had the same field layout and packing. Note that this function is designed to work only with classes with the [StructLayout] attribute with a LayoutKind of either Explicit or Sequential.

The memory used up when the CLR allocates an object on the managed heap depends on the internals of the CLR in question. Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects is an article about the CLRv2 implementation of object allocation. Essentially, every object has two hidden fields - a sync block index and a type handle. The sync block is an internal structure used when an object is used with a lock(obj) {} statement. The type handle provides runtime type information about the given instance - it contains the object's method table, etc.

Stefan Dragnev
  • 14,143
  • 6
  • 48
  • 52
0

Indeed, a class in C# is not just the fields id contains. There has to be a virtual functions tables so you can use virtual & override keywords, and certainly few other things, like maybe a pointer to the type metadata...

The fact is you should not care... what's important is "how many bytes do I need to be able to rebuild the instance?". The answer is what Marshal.SizeOf gives you : 4.

Marshalling only the 4 bytes of the integer (yes you're right, it's 4 bytes), and knowing you want to deserialize a MyClass, then you have enough information to do it.

Kek
  • 3,145
  • 2
  • 20
  • 26