Binary Serializations DataContracts Vector2

Using tagged(token) txt loading for now, but was testing out reading and writing in binary. It seems I can do this ok but any class which contains Vector2, etc… I notice it says not serializable. So I looked and found out it uses something called [DataContract] and found some info which seemed to indicate that it would work if I used that instead. Added the needed assembly reference and using, tried it out – it would write to file but won’t read it (says passed end of file before done parsing?) … Did some more research on it and now even more confused. Marking thousands of fields as DataMember (o-o) Still no.
[Also noticing that I had to add a binding class to allow it to use data between different projects]
I’ve been searching and all I find is stuff on BinaryFormatter – I’m wondering if anyone knows what the standard or semi-standard easy way of writing-reading a chunk / class-memory as binary right now. I’m used to doing this in C++ which so far seems extremely simple by comparison as far as binary files go. (O__O)’’

[ I’ll update this post if I figure out a good way. ;p ]

I use binary serialization a lot, and have never used the Serializable or DataContract attributes. I use BinaryReader and BinaryWriter to explicitly serialize the fields I want and in the order I want.

I usually add Serialize(BinaryWriter writer) and Deserialize(BinaryReader reader) methods to the classes to be serialized.

For example, say the class has the following fields

Vector2 position;
float speed;

The serialization i would write would be

public void Serialize(BinaryWriter writer)

public void Deserialize(BinaryReader reader)
    position.X = reader.ReadSingle();
    position.Y = reader.ReadSingle();
    speed = reader.ReadSingle();

I usually add versioning to it as well, so that changes to the class can still load older versions of the data. That goes beyond the original question though, so I’ll leave for another time if you want to know more.

1 Like

Ah - that’s perfect. I like it. Especially with putting these directly in each class. Easy to see all the fields you need.
Yeah, I can see where versioning would come in handy.
Right now I’m using text files with switch case for tokens so that as it changes I add a new token. I thought once I’m pretty sure nothing new will be added I can move to binary but it’s still bound to change down the road. :wink:
Thanks :smiley:

Try using ISerializationSurrogate:

sealed class Vector2SerializationSurrogate : ISerializationSurrogate
public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
var vec = (Vector2)obj;
info.AddValue(“x”, vec.X);
info.AddValue(“y”, vec.Y);

    public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        var vec = (Vector2)obj;
        vec.X = info.GetSingle("x");
        vec.Y = info.GetSingle("y");
        return vec;
1 Like