I would like to deepen my understanding of data types and want to know how I can determine how big a data type is. I'm hoping the journey to the answer uncovers other unknowns.
I know that in .NET, a byte is an 8-bit unsigned integer, but only because I've read about it. If I have a very simple console app like the following:
static void Main(string[] args)
{
byte b = 1;
}
How can I tell in Visual Studio, how big the data structure of 'b' is? I see that there are some Memory diagnostic windows but it only says that they're unable to evaluate the expression when I step over the assignment of b. I have the Disassembly window open and can see the mov op...
mov dword ptr [ebp-40h],1
... but not sure what the information means. I'm thinking that dword is hinting at the size and perhaps ptr ebp-40h is pointing to an address. Is there a way I can see all of the addresses in Visual Studio and perhaps glean the size by looking at the range?
I know these are tough questions to answer in a short forum like this but thanks for any help.
You can use sizeof(T)
to get the size of primitive value types and non-reference types. For other types, it can be very difficult to obtain the size, because reference types generally do not have a fixed size.
This can be a complex issue outside simple types (per the discussion below), but generally, if the size of a type is not defined explicitly by its data structures because it is itself a reference type, or it is a structure that contains reference types, then there is no way to calculate storage (since it is, by definition, not fixed).
tl;dr: sizeof(YourType)
should give you "the answer", but Marshal.SizeOf
may be more appropriate.
That doesn't always work. C# doesn't like you breaking its abstraction barrier, so it only lets you find the "size" of a structure if the structure has the same size in managed and unmanaged code (or, more accurately, is "blittable"). Otherwise, C# claims, "why do you care about the managed size? It's useless to you", and doesn't let you take the sizeof
of a managed type.
There are ways to get around this (through direct MSIL generation), but if you in fact want the size of the unmanaged representation of the same object, then you probably want to use Marshal.SizeOf
instead. sizeof
is actually not as useful as it seems -- it's just more handy.
There is also a hardcore SOS option, which will give you a true value for the size of an object.
Use !ObjSize
command
==Immediate Window==
.load sos
!ObjSize <address>
You may need to poke around to get the address of the object. Check the !Dump*
commands, like !DumpHeap
and !DumpStack
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With