I\'m looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?
I had a similar question recently and wanted to know the size of Object and LinkedListNode in C#. To solve the problem, I developed a program that would:
On my computer (64-bit), I got the following data:
Measuring Object:
iter working set size estimate
-1 11190272
1000000 85995520 74.805248
2000000 159186944 73.998336
3000000 231473152 73.4276266666667
4000000 306401280 73.802752
5000000 379092992 73.580544
6000000 451387392 73.3661866666667
7000000 524378112 73.3125485714286
8000000 600096768 73.613312
9000000 676405248 73.9127751111111
Average size: 73.7577032239859
Measuring LinkedListNode
Based on the data, the average size of allocating millions of Objects is approximately 29.2 bytes. A LinkedListNode object is approximately 44.5 bytes. This data illustrates two things:
Assuming CLR overhead and 4-byte alignment, I'd estimate an Object in C# is 28 bytes and a LinkedListNode is 44 bytes.
BTW Jon Skeet had the idea for the method above before I did and stated it in this answer to a similar question.