2

Is there any way to get the size of an instance (or the class I don't mind) in C#?

For example, I know in Delphi every object has a pointer to the Virtual Method Table of the class, a pointer for each interface it implements plus of course the fields of the class.

According to this basic object size is 12 bytes in x86, but, is there any "rule" to properly size it?

Community
  • 1
  • 1
Jorge Córdoba
  • 51,063
  • 11
  • 80
  • 130
  • 1
    Just curious: why? What will you use this for? – Joel Coehoorn May 14 '09 at 14:12
  • 2
    Duplicate: http://stackoverflow.com/questions/207592/getting-the-size-of-a-field-in-bytes-with-c#207605 – Jon Skeet May 14 '09 at 14:21
  • So there's no way to calculate it "theroretically", just by measuring with the GC? – Jorge Córdoba May 14 '09 at 15:09
  • Joel, I need to create a great quantity of objects in order to emulate a knowledge base in memory and I want to estimate the size I'll be dealing with. I'd like to measure also the impact of implementing "to many" interfaces in the classes used to represent the "tables" of the database. – Jorge Córdoba May 14 '09 at 15:16
  • So create a great many of them and take a look at how much memory your program uses as a result. Always measure the _actual quantity you're interested in_ if possible; don't measure something completely different and then try to guess what the relationship is with the figure you actually care about. – Eric Lippert May 14 '09 at 15:31

1 Answers1

3

It depends on what you are looking to do. If you are interested in finding out how big a type / object will be for the purpose of interop with native code, you can use Marshal.SizeOf(). Other than that, there is no definitive way to measure an object's size.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454