简体   繁体   中英

How to determine size of an object, c#?

I have the following class:

public class MyClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public double Amount { get; set; }
    } 

When I try to find out size of this class on a 64 bit system by using WinDbg I get the size 40 which I am not able to understand, as far as I have read MyClass should have

8 bytes for SyncBlock
8 bytes for TypeHandle
8 bytes for string reference
4 bytes for Int32
8 bytes for double

= 36 bytes

I don't have 10 reputation that's why i am not able to post image. Anyone has any idea why WinDbg is showing 4 extra bytes ?

I believe what you're seeing is the effect of things needing to align to 8 byte boundaries in 64 bit builds (and 4 byte boundaries in 32 bit builds). 40 is the closest size >= 36 that is on an 8 byte boundary. These links talk about object size:

Of Memory and strings (Jon Skeet's blog)

Benchmarking C# Struct and Object Sizes

Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects

How Much Memory Does a C# String Take Up

It is due to the padding for types to fit on address boundaries.

This will depends on the types you are using, the runtime and the StructLayoutAttribute used for the type.

if you look at Int32 with reflector you will see:

StructLayout(LayoutKind.Sequential)

This means that it can be noncontiguous :

The members of the object are laid out sequentially, in the order in which they appear when exported to unmanaged memory. The members are laid out according to the packing specified in StructLayoutAttribute.Pack, and can be noncontiguous.

The StructLayoutAttribute.Pack value is unset this means that it is 0 (defaultvalue)

A value of 0 indicates that the packing alignment is set to the default for the current platform. It is usually 4byte for x86 and 8byte for x64 but it is optimized by the CLR in base of the sistem and those value may vary

You can see it with:

#pragma pack(show)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM