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

  • Thread starter Thread starter Lei Jiang
  • Start date Start date
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!
 
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
 
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
 
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.
 
Back
Top