4
votes

I've been able to serialize nullable doubles without an issue, and can serialize Lists of nullable other types, but can't serialize Lists of nullable doubles.

If I do this:

        List<double?> aList = new List<double?>();
        aList.Add(0.1);
        aList.Add(null);
        Serializer.Serialize(ms, aList);

I get this error:

System.NullReferenceException: Object reference not set to an instance of an object. at ProtoBuf.Meta.TypeModel.TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, Int32 tag, Object value, Boolean isInsideList) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 169 at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 188 at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 217 at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 201 at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) in c:\Dev\protobuf-net\protobuf-net\Serializer.cs:line 87

should this work? Am I doing something wrong?

1
I put a test together with a List<int?>, a List<double?> and a List<string> - they all behaved identically hereMarc Gravell♦
I'll rerun my test and returnmcmillab
I get the same behaviour will all nullable types. I think previously whilst I had nullable types, it was only the nullable double that had actual null values. Apologies for the misinformation. Benmcmillab

1 Answers

3
votes

The main problem here is that the protobuf specification simply has no concept of null - explicitly null / missing values cannot be expressed in the protobuf format.

On a per-library basis, the library itself could choose to spoof an extra layer to allow for this kind of thing, but:

  • it would take extra bytes on the wire
  • it would complicate the code and require extra configuration
  • it would (by necessity) disable optimisations like "packed" encoding

It should probably detect the null and behave better, though!

I would encourage you to serialize a list of things that have a nullable-value, rather than a list of null able values themselves. For example:

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

A list of the above can express null values. And is basically exactly the same as what I would write if I added inbuilt support for spoofing nulls.