Find out the size of a .NET object

If you can - Serialize it!

Dim myObjectSize As Long

Dim ms As New IO.MemoryStream
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(ms, myObject)
myObjectSize = ms.Position

Don't forget that the size of an actual object doesn't include the size of any objects it references.

The only things which are likely to end up on the large object heap are arrays and strings - other objects tends to be relatively small in themselves. Even an object with (say) 10 reference type variables (4 bytes each on x86) and 10 GUIDs (16 bytes each) is only going to take up about 208 bytes (there's a bit of overhead for the type reference and sync block).

Likewise when thinking about the size of an array, don't forget that if the element type is a reference type, then it's only the size of the references that count for the array itself. In other words, even if you've got an array with 20,000 elements, the size of the array object itself will only be just over 80K (on x86) even if it references a lot more data.


You are getting into an area of advanced .NET debugging. Start with John Robins debugging books.

Use WinDBG with Sos.dll (part of .NET distribution) and Sosex.dll extensions. With these tools you can really see what's happening when your application is running. You will find answers to your above mentioned questions.

(Another recommendation would be to install Shared Source CLI 2.0, aka. Rotor 2, to see what's going on under the hood.)


Please follow these steps to get the size of the object.

  1. Go to Visual Studio 2010 Project Properties → Debug tab → Enable unmanaged code debugging.

  2. Go to the Visual Studio Debug menu → Options and SettingsDebuggingSymbols.

  3. There, enable Microsoft Symbol Server and leave the default (symbols may start a download).

  4. Set the breakpoint in your code, start debugging (F5).

  5. Open DebugWindowsImmediate Window.

  6. Enter .load sos.dll (Son of Strike)

  7. Enter !DumpHeap -type MyClass (the object you want to find the size of)

  8. From the output, locate the address of the object, i.e. (00a8197c)

    Address MT Size 00a8197c 00955124 36

  9. Next, !ObjSize 00a8197c

  10. There you go → sizeof(00a8197c) = 12 (0x48) bytes (MyClass)