views:

200

answers:

3

I renamed the class classBattle to Game and not I get "Unable to load type battle.classBattle+udtCartesian required for deserialization."

This is the line of code MapSize = (Game.udtCartesian)formatter.Deserialize(fs);

How do I fix this? Does this mean I cannot rename classes?

+1  A: 

When serializing if not using contracts, the name of the class is part of it, so it stands to reason that to deserialize the class name needs to be the same.

You can change the class name, serialize again and deserialize without a problem.

What will not work is serializing with one name and attempting to deserialize back to a different name.

Other then that, use contracts and a formatter that uses them.

Oded
+3  A: 

BinaryFormatter is brittle, and is not designed to be friendly if you have changes to the types involved. If you want that type of behaviour, you need a contract-based serializer such as XmlSerializer, DataContractSerializer or protobuf-net. Anything except BinaryFormatter.

Marc Gravell
I was going to post an answer recommending http://code.google.com/p/protobuf-net but I will defer to Marc (who wrote it!).
Ben Challenor
A: 

Hi Fred,

you could also use a SerializationBinder to define which type will be loaded in the case that another type is being deserialized:

public sealed class Version1ToVersion2DeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        Type typeToDeserialize = null;

        if (typeName == "OldClassName")
            typeName = "NewClassName";

        typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
                typeName, assemblyName));

        return typeToDeserialize;
    }
}

To deserialize, you just have to set the Binder Property of the BinaryFormatter:

formatter.Binder = new Version1ToVersion2DeserializationBinder();

NewClassName obj = (NewClassName)formatter.Deserialize(fs);

Regards

Lumo