Fred F.
Fred F.

Reputation: 423

When I renamed a class I am getting a deserialization error. How to fix it?

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?

Upvotes: 4

Views: 4771

Answers (4)

Omar Salem
Omar Salem

Reputation: 156

If you are not concerned about saved data, just delete the file, the new one will be saved using new name.

Upvotes: 0

user316514
user316514

Reputation: 59

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);

Upvotes: 5

Oded
Oded

Reputation: 499072

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062975

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.

Upvotes: 4

Related Questions