tags:

views:

2131

answers:

4

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?

+7  A: 

You need Marshal.SizeOf

Edit: This is for unsafe code, but then, so is sizeof().

Greg Hurlman
Marshal.SizeOf might return a different number of bytes than the number used.
Thomas Bratt
A: 

Beware that Marshal.SizeOf is for unsafe code...

I don't think it's possible for managed code though, maybe you can explain your problem, there may be another way to solve it

Juan Manuel
A: 

It's not a problem, just a curiosity exercise. I have a bunch of items going into HttpContext.Items throughout a request, and I was just curious how much memory they were taking up (if it even matters). I'm going through a "measure everything" phase.

John Sheehan
There are other ways to determine this (without code modification). Just use a memory profiler. Any decent profiler will show you number of bytes allocated per particular instance and also all memory that is held by the instance, including memory taken by referenced instances.
Marek
+4  A: 

If you don't mind it being a little less accurate than perfect, and for comparative purposes, you could serialize the object/s and measure that (in bytes for example)

EDIT (I kept thinking after posting): Because it's a little more complicated than sizeof for valuetypes, for example: reference types can have references to other objects and so on... there's not an exact and easy way to do it that I know of...

Juan Manuel