Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does binaryformatter serializes objects?

BinaryFormatter behaving in weird way in my code. I have code like following

[Serializable]
public class LogEntry
{        
    private int id;

    private List<object> data = new List<object>();

    public int Id
    {
        get { return id; }
    }

    public IList<object> Data
    {
        get { return data.AsReadOnly(); }
    }
    ...
}
....
....
private static readonly BinaryFormatter logSerializer = new BinaryFormatter();
....
....
public void SerializeLog(IList<LogEntry> logEntries)
{
        using (MemoryStream serializationStream = new MemoryStream())
        {
            logSerializer.Serialize(serializationStream, logEntries);
            this.binarySerializedLog = serializationStream.GetBuffer();
        }
}

In some machine (32 or 64 bit machine), it is serializing in binary format - which is expected. But in some machine ( all of them are 64 bit machine and not for debug builds) it is not serializing, binarySerializedLog is showing ToString() value of all individual Data, class name (...LogEntry) and id value. My question is - are there specific reason for this type of behavior or am I doing some mistake? Thanks in advance.

like image 449
malay Avatar asked Feb 18 '26 17:02

malay


1 Answers

Your question isn't very clear (can you define "not serializing"?), but some thoughts:

You should really use ToArray() to capture the buffer, not GetBuffer() (which is cheaper, but returns the oversized array, and should only be used in conjunction with Length).

Where are you seeing this .ToString()? BinaryFormatter writes the objects type, then either uses reflection to write the fields (for [Serializable]) or uses customer serialization (for ISerializable). It never calls .ToString() (unless that is what your ISerializable does). However, strings etc will be in the output "as is".

Note that BinaryFormatter can be brittle between versions, so be careful if you are keeping this data for any length of time (it is generally fine for transport, though, assuming you update both ends at the same time). If you know in advance what your .Data objects are, there are a range of contract-based serializers that might provide more stability. I can provide more specific help if you think this would be worth investigating.

like image 169
Marc Gravell Avatar answered Feb 20 '26 05:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!