It depends on what you want. If you want to know the exact size you will occupy it is quite difficult. If you accept an approach there gives, but I do not know if the approach is so useful.
Denis' answer gives an approximation.
Another way is to get the size of the type with the operator sizeof
. If you know the object, you know its type. It even works with generics. If you know C, it works the same. Only in C# it is little needed.
The returned value does not include the overhead that each object has to allocate in the heap, if it is the case to allocate there. The account of the overhead is a bit complicated and can vary from version to version, although I’ve never seen change. Today is the size of two CPU words. If you’re in the stack has not overhead, when it’s inside another object in place neither.
Note that if the object contains references, there are other objects that are occupying space as well and it is your problem to detect this and check the entire object graph.
It also complicates when you have array involved, then you have to ask him his size and multiply by the size of the type he carries.
The Runtime does some magic. I don’t know what would happen in cases like this. I can’t trust.
In fact there are so many other things that can influence memory occupation that it is very difficult to know this beforehand.
I don’t like the solution of Arthur, Mathias and LINQ, even if it is the best effort, because it is also inaccurate, you have no control over GC. The allocation is not so linear. If you ask for 4 bytes it won’t change 4 bytes, it can change nothing, it can change more, it depends on the organization of the memory and even how the GC is working in that version. And if you’re in stack will change nothing, so it may seem that the size is 0.
I do not consider any answer here wrong, only there is no precision and this needs to be in the answers to completeza. My opinion.
I guess you’re not talking about unmanaged memory. This can be identified with Marshall.SizeOf()
.
So my answer is that precisely it does not. Imprecise gives but it does not have much use. . NET is not a suitable platform for this type of thing. If you really need to control the allocation goes from C. Even C++ can complicate some things.
The truth is that there is no precise method to return the in-memory size of an object.
– LeonanCarvalho
@Leonancarvalho yes. And I was even researching to see if I ate ball.
– Maniero
Highlight for "I do not consider any answer here wrong, only there is no precision and this needs to be in the answers to completeza. My opinion.", fully agree.
– LeonanCarvalho