How can I know the size of a managed reference type?

L

Lei Jiang

I'd like to calculate the memory size that my data structure cost, but I
could not find any API that I could calculate the size of an object. Could
anyone give me a work around?

Thanks!
 
B

Bob Powell [MVP]

Marshal.SizeOf

--
Bob Powell [MVP]
Visual C#, System.Drawing

The Image Transition Library wraps up and LED style instrumentation is
available in the June of Well Formed for C# or VB programmers
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

The GDI+ FAQ RSS feed: http://www.bobpowell.net/faqfeed.xml
Windows Forms Tips and Tricks RSS: http://www.bobpowell.net/tipstricks.xml
Bob's Blog: http://bobpowelldotnet.blogspot.com/atom.xml
 
B

Bob Powell [MVP]

public struct aStruct

{

public int i;

public char c;

public double d;

}


aStruct a=new aStruct();

MessageBox.Show("SizeOf aStruct="+Marshal.SizeOf(a).ToString());


This seems to work. What are you having trouble with?

--
Bob Powell [MVP]
Visual C#, System.Drawing

The Image Transition Library wraps up and LED style instrumentation is
available in the June of Well Formed for C# or VB programmers
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

The GDI+ FAQ RSS feed: http://www.bobpowell.net/faqfeed.xml
Windows Forms Tips and Tricks RSS: http://www.bobpowell.net/tipstricks.xml
Bob's Blog: http://bobpowelldotnet.blogspot.com/atom.xml
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Bob,

Marshal.SizeOf return the size of the type when it is marshaled. In other
words the size of the unmanaged representation of the type. Type's size in
the managed environment doesn't make sense that's why there is no mathod or
instruction to find it.

The latter is not completely true.There is *sizeof* instruction in C#, which
however works only in usnafe mode, only with value types and AFAIK it
returns the managed size of the type. *sizeof* and Marshal.SizeOf may return
different values in some cases.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top