3

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.

dav_i
  • 27,509
  • 17
  • 104
  • 136
  • If you're serializing with the BinaryFormatter you don't have to care about public properties, it'll serialize only fields (in your case _celcius). Moreover if you want to save your data to use the default formatter isn't a good idea because of its "proprietary" format and the way it handles versions. – Adriano Repetti May 22 '12 at 09:29
  • So you're saying that as long as I keep `_celcius` in there, it doesn't matter what I do with the surrounding code? Could you please expand a little on your second sentence, please? – dav_i May 22 '12 at 09:34
  • 1
    Yes, you can add as many public properties as you need. For comparison take a look at this post here on SO: http://stackoverflow.com/questions/1154198/what-are-the-differences-between-the-xmlserializer-and-binaryformatter – Adriano Repetti May 22 '12 at 09:38

2 Answers2

1

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

Community
  • 1
  • 1
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

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.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114