C#, what is the size?

Started by
4 comments, last by Infinisearch 8 years, 2 months ago

consider following class

public class A
{

int gh;

int dk;

int fg;

int gha;

int dkd;

int fgf;

}

and then class

public class B
{

public A m_p1=null;

public A m_p2=null;

public A m_p3=null;

}

What will be the byte size of class B? Will it be three pointers, or, three times the size of class A?.

Advertisement

Three pointers.

-potential energy is easily made kinetic-

You really don't have any guarantees about what the CLR will do with your class. There's a very good explanation of that here

If you want to know how much unmanaged memory a class or struct will take up if you need to interop, you can use Marshal.SizeOf().

Eric Richards

SlimDX tutorials - http://www.richardssoftware.net/

Twitter - @EricRichards22

What will be the byte size of class B? Will it be three pointers, or, three times the size of class A?.

It depends. The effective size of an instance of B will scale in proportion to the size the CLR requires for a reference, since A is a reference type and B contains three of them. It will be roughly 3R + O, where "R" is the size required for a reference and O represents some instance-specific overhead which may be zero. Basically this is not information that is provided to you outside of specific implementation internals.

More importantly, why does this matter to you? What are you actually trying to solve?

If you want to know how much unmanaged memory a class or struct will take up if you need to interop, you can use Marshal.SizeOf().

It's probably worth noting that Marshal.SizeOf() cannot be use on either of the two type presented by the OP, as they cannot be marshalled as an unmanaged structure. Marshal.SizeOf can't be used on any arbitrary type.

Clr Via C# is a good source for this kind of question.

It's relevant to know what kind of size are you talking about?
The consumption of class variables in memory?

The size of the class itself? (Inlucding memory tables(Methods,meta data) and meta data(used by reflection))

For your direct question:

It depends what you're asking. The physical size of the class will be three pointers because A is enscapulated as a pointer under a C# reference.

If you ask for overall size, it will the size of B + 3 times the size of A.

Some performance counters and matrices state the later while some will give you direct answer for the former.

WinDBG is a great tool to check that kind of sizes.

Mr. Petrie is more correct than I am as he took into account per instance overhead and used the term reference instead of pointer. One example of per instance overhead would be the type of the object. (if I'm not mistaken that is)

-potential energy is easily made kinetic-

This topic is closed to new replies.

Advertisement