Question

i'm a complete beginner with protobuf-net so probably this is just some stupid beginner mistake. But i cant find whats the problem with this:

I have a class thats to be serialized to disk defined like this:

[ProtoContract]
public class SerializableFactors
{
    [ProtoMember(1)]
    public double?[] CaF {get;set;}

    [ProtoMember(2)]
    public byte?[] CoF { get; set; }

}

and a Test defined like this:

        if (File.Exists("factors.bin"))
        {
            using (FileStream file = File.OpenRead("factors.bin"))
            {
                _factors = Serializer.Deserialize<SerializableFactors>(file);
            }
        }
        else
        {
            _factors = new SerializableFactors();
            _factors.CaF = new double?[24];
            _factors.CaF[8] = 7.5;
            _factors.CaF[12] = 1;
            _factors.CaF[18] = 1.5;
            _factors.CoF = new byte?[24];
            _factors.CoF[8] = 15;
            _factors.CoF[12] = 45;
            _factors.CoF[18] = 25;
            using (FileStream file = File.Create("factors.bin"))
            {
                Serializer.Serialize(file, _factors);
            }
        }

So basically if the file doesnt exist yet i create a object with default values and serialize it to disk. If the file exists i will load it into memory.

BUT the result for me on loading the file is not what i created before the saving to disk. I create arrays with length 24 which have values in the slots 8, 12 and 18. But the deserialized object has arrays of the length 3 which hold my values.

What is my mistake in here? Thanks in advance!

Was it helpful?

Solution

You must set the RuntimeTypeModel to support null

See the following post: How can I persist an array of a nullable value in Protobuf-Net?

// configure the model; SupportNull is not currently available
// on the attributes, so need to tweak the model a little
RuntimeTypeModel.Default.Add(typeof(SerializableFactors), true)[1].SupportNull = true;

if (File.Exists("factors.bin"))
{
   using (FileStream file = File.OpenRead("factors.bin"))
   {
      _factors = Serializer.Deserialize<SerializableFactors>(file);
   }
}
else
{
   _factors = new SerializableFactors();
   _factors.CaF = new double?[24];
   _factors.CaF[8] = 7.5;
   _factors.CaF[12] = 1;
   _factors.CaF[18] = 1.5;
   _factors.CoF = new byte?[24];
   _factors.CoF[8] = 15;
   _factors.CoF[12] = 45;
   _factors.CoF[18] = 25;
   using (FileStream file = File.Create("factors.bin"))
   {
     Serializer.Serialize(file, _factors);
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top