Link to home
Start Free TrialLog in
Avatar of ba272
ba272

asked on

Need to find the size of my object

Greetings,

Is there a SizeOf() function in C# that can tell me the size of an object?  I see quite a few in the help, but I would rather not test them all, so if anyone has experience with one, I'd be grateful.

Please include the namespace as well.

Thanks.

ASKER CERTIFIED SOLUTION
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ba272
ba272

ASKER

Greg,

I was actually just thinking about finding the size of an object.  For example, a DateTime object.  Or an object of my own.


Thanks,

Bob
There are many problems doing this with object graphs ... for an individual object count its value types/sizes

http://dotnetjunkies.com/WebLog/bikta/articles/17084.aspx

discusses other methods of estimation (binary serialization) but any method is at best a hack ... The reason you can't get this is incase the internal implementations change, providing this information leaves you the possibility of bcoming dependant upon layouts/sizes

Greg
SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
its listed in the above example, the problem is that is its marshalled size not its memory size ... object graphs are a real pain to determine the size of :)
Avatar of ba272

ASKER

Greg,

When you say object graphs, are you thinking about objects like DateTime, for example?


Bob
I am more worried about complex objects (an objects size is determined by its size plus the size of any objects it references)... assume a typed collection foo below ...

public class A {
    public fooCollection B;
}

public class foo {
   public A parent;
}

this for instance would be a real pain to find ... because both objects reference each other thus you would need to remember both in memory as you walked the objects to determine the true size (otherwise you would recurse infinitely). The other problem is often times you end up with one object that has hundreds of thousands of objects it references indirectly (look at a control).

Greg

Avatar of ba272

ASKER

Okay, I understand youir concern.  But how about finding the size of a DateTime object?  Do you have a methodolgy which woud yield a size which you'd have some confidence in?  That particular object is the one which is of most interest to me.

Thanks,
Bob
I would use a sum of all of its value types (can get easily through reflection) and forget about references (although they do use memory).

Greg