mark
mark

Reputation: 62774

How to serialize a non List<T> collection in protobuf-net?

Observe the following code:

[ProtoContract]
public class C
{
  [ProtoMember(1)]
  public IList<string> Tags { get; set; }
}

class Program
{
  static void Main()
  {
    var m = RuntimeTypeModel.Default;
    m.AutoCompile = true;
    m.Add(typeof(IList<string>), false).AddSubType(1, typeof(ObservableCollection<int>));

    var c = new C { Tags = new ObservableCollection<string> { "hello" } };
    using (var ms = new MemoryStream())
    {
      Serializer.Serialize(ms, c);
      ms.Position = 0;
      var c2 = Serializer.Deserialize<C>(ms);
      Debug.Assert(c.Tags.Count == c2.Tags.Count);
      Debug.Assert(c.Tags.GetType() == c2.Tags.GetType());
    }
  }
}

The last assertion fails, because c2.Tags is a regular List<T>, rather than ObservableCollection<T>. In effect, the AddSubType statement is ignored.

Is it possible to fix it without using surrogates?

Upvotes: 2

Views: 375

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062925

Lists etc are mapped to the "repeated" syntax from the .proto spec. This embeds directly from the parent object directly. There is no facility to store any additional metadata.

The code has been tweaked to highlight this rather than silently ignore it.

You can specify the default concrete type to use, but only that.

Upvotes: 1

Related Questions