dav_i
dav_i

Reputation: 28117

C# Serialization practices of object with custom types

I've created some custom types for example:

public class Temperature
{
    protected double _celcius;

    public Temperature(){}

    public Temperature(double celcius)
    {
        _celcius = celcius;
    }

    public double Celcius
    {
        //sets & returns temperature in Celcius
    }

    public double Fahrenheit
    {
        //sets & returns temperature in Fahrenheit
    }
}

and a similar one for Mass, etc.

I also have a custom object, for example Planet, which uses these custom types as properties.

[Serializable]
public class Planet
{
    public int PositionFromSun;
    public Mass Mass;
    public Temperature Temperature;
}

What is the best practice for serializing Planet in this case considering that Mass and Temperature may change slightly in the future (e.g. adding Kelvin to Temperature)? Should I have Mass and Temperature inheriting from a custom interface of something like IQuantity.

Upvotes: 3

Views: 678

Answers (2)

dav_i
dav_i

Reputation: 28117

Please see @Adriano's comment. This is what I needed.

Yes, you can add as many public properties as you need. For comparison take a look at this post here on SO: What are the differences between the XmlSerializer and BinaryFormatter

Upvotes: 1

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

Binary serialization is quite picky about properties being added and removed to types. If you use a version tolerant serializer (eg xml based serialisers) you'll be able to reliably serialize / deserialise between versions of classes.

You may want to consider using protobuf.Net for your serialization - it is mature, very very quick and version tolerant.

Upvotes: 0

Related Questions