Sign in to follow this  
toxi

[.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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this