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

## Recommended Posts

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++.

##### Share on other sites
Marshal.SizeOf(typeof(Foo));

Regards,
ViLiO

##### Share on other sites
But this will word only for unmanaged object... :(
I need to get size of managed object...?

##### Share on other sites
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.

##### Share on other sites
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."

##### Share on other sites
guys, you are great!
Thanks a lot!
SnOrfys, this is precisely what i need!

Thank you all again!

##### Share on other sites
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?

##### Share on other sites
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.

##### Share on other sites
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.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627638
• Total Posts
2978330

• 10
• 12
• 22
• 13
• 34