Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to determine size of complex object in .NET?

Are there ways at determining the total size of a complex object in .NET? This object is composed of other objects and might hold references to other complex objects. Some of the objects encapsulated by this object might be POD, others may not.

like image 244
Polaris878 Avatar asked Jun 16 '10 21:06

Polaris878


People also ask

How do I get the size of an object in C#?

C# has a 'sizeof' operator that works like it does in C++, however it returns the size that a field of that type will be. Thus for reference types (class, not struct), it will always return the size of a pointer (4 on 32 bit systems).

What are complex objects in c#?

Complex objects are the objects that are built from smaller or a collection of objects.

What is size of an object class in C#?

The size of a class is the total size of all members of that class. You really need to buy a basic c# book and read up about DataTypes and their sizes, this is really elementary stuff you should know before anything else.

Which function can be used to give size of any object?

The sizeof operator gives the size of the object or type.


1 Answers

What you have is not a "complex object", it's an object graph. To determine its total size, you need to walk that graph - starting with some root object, and using Reflection to enumerate fields of reference types and retrieving their values (and checking for loops, of course).

To get the size of a particular object in the graph, see this answer to a related question, but note that this is an evil hack, completely unsupported, may break (and may already be broken), and may result in a wholesale kitten genocide in heavenly spheres. That said, there is no "non-hacky" way to get a precise value, because it is an implementation detail by definition - you shouldn't have any use for it. And for the purpose of finding out the memory usage of an app during debugging/profiling, the hack is good enough.

like image 83
Pavel Minaev Avatar answered Sep 24 '22 14:09

Pavel Minaev