9

I'm using the latest version of ProtoBuf on NuGet (2.0.0.480) and it does not serialize types marked with DataContract/DataMember attributes:

[DataContract]
public class Person
{
    [DataMember]
    public string Firstname { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "person.dat");

        var person = new Person { Firstname = "ben" };

        using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate)) {
            Serializer.Serialize(fs, person);
        }

        using (var fs = File.OpenRead(outputFile))
        {
            var result = Serializer.Deserialize<Person>(fs);
            Console.WriteLine(result.Firstname);
        }

        Console.ReadLine();
    }
}

However, if I decorate my class using the ProtoBuf specific attributes:

[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public string Firstname { get; set; }
}

It works as expected.

Ben Foster
  • 34,340
  • 40
  • 176
  • 285

3 Answers3

12

It needs the Order property to get a unique and reliable key-number:

[DataContract]
public class Person
{
    [DataMember(Order=1)]
    public string Firstname { get; set; }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

I should have read the docs more closely, when using [DataMember] an Order must be specified.

e.g.

[DataMember(Order = 1)]

Ben Foster
  • 34,340
  • 40
  • 176
  • 285
2

In addition to Marc and Ben answers, note that you have to set the order values greater than 0.
we used to start the order from 0 when using the BCL serializers but protobuf-net is ignoring data members with order as 0.

Tamir
  • 3,833
  • 3
  • 32
  • 41