Find size of object instance in bytes in c#

First of all, a warning: what follows is strictly in the realm of ugly, undocumented hacks. Do not rely on this working – even if it works for you now, it may stop working tomorrow, with any minor or major .NET update.

You can use the information in this article on CLR internals MSDN Magazine Issue 2005 May – Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects – last I checked, it was still applicable. Here’s how this is done (it retrieves the internal “Basic Instance Size” field via TypeHandle of the type).

object obj = new List<int>(); // whatever you want to get the size of
RuntimeTypeHandle th = obj.GetType().TypeHandle;
int size = *(*(int**)&th + 1);
Console.WriteLine(size);

This works on 3.5 SP1 32-bit. I’m not sure if field sizes are the same on 64-bit – you might have to adjust the types and/or offsets if they are not.

This will work for all “normal” types, for which all instances have the same, well-defined types. Those for which this isn’t true are arrays and strings for sure, and I believe also StringBuilder. For them you’ll have add the size of all contained elements to their base instance size.

Leave a Comment