[.net] How to get size of some object?

Started by
7 comments, last by TheUnbeliever 16 years, 8 months ago
First, i will like to thank you for helping me this far ;) My new question is short - how i can get a size of some object using C# and .NET framework 2.0? That is, something like sizeof in C++.
Advertisement
Marshal.SizeOf(typeof(Foo));

Regards,
ViLiO
Richard 'ViLiO' Thomasv.net | Twitter | YouTube
But this will word only for unmanaged object... :(
I need to get size of managed object...?
if it were serializable, I could tell you:

using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;/* ... */            BinaryFormatter bFormatter = new BinaryFormatter();            MemoryStream ms = new MemoryStream();            bFormatter.Serialize(ms, myObject);            MessageBox.Show(ms.Length.ToString());


otherwise... I couldn't tell you.
I don't think there's a way to do this, by design.

Chris Brumme's words on the matter:

"We don't expose the managed size of objects because we want to reserve the ability to change the way we lay these things out. [...] But we don't want to provide an API, because then you could form a dependency over this implementation detail."
[TheUnbeliever]
guys, you are great!
Thanks a lot!
SnOrfys, this is precisely what i need!

Thank you all again!
In general, there are no assurances that the serialized form of an object bears any resemblance to its form when deserialized, and therefore there is no guarantee that the above will work. Any class that inherits from ISerializable can specify how parts of the class are serialized, and it isn't necessarily the case that all fields will be serialized — any marked with NonSerializedAttribute won't.

What are you trying to do that requires getting the size of a managed object?
[TheUnbeliever]
I need to send whole object to another computer using sockets. By serializing it in some MemoryStream i will then be available to first get byte array( that will contain that object data) and then send that byte[] across network. I will know how much byte[] is send so i will know how mach of them i will reciving on remote computer.


Sorry for broken english.
Ah, in that case, then the solution given is absolutely perfect since you need to serialize/deserialize any way (must use serialization to transport objects between application domains, as is the case here) and you want the size of the serialized data rather than the object itself.

Don't worry about your English, it's perfectly comprehensible. :-)
[TheUnbeliever]

This topic is closed to new replies.

Advertisement