Sign in to follow this  

C#, what is the size?

This topic is 674 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?.

Share this post


Link to post
Share on other sites
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.
Edited by Josh Petrie

Share this post


Link to post
Share on other sites

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. 

Share this post


Link to post
Share on other sites

This topic is 674 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this