6

protogen.exe generates this pattern for a proto2 message field of type long :

private long _Count = default(long);
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"Count", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(long))]
public long Count
{
  get { return _Count; }
  set { _Count = value; }
}

but as proto2 does not include a date-time type ( and protobuf-net does not support proto3 which includes google.protobuf.Timestamp ) it's not clear how to represent DateTime in manually coded C# proto object.

This is probably wrong :

private DateTime _When = DateTime.MinValue;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"When", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(DateTime.MinValue)]
public DateTime When
{
  get { return _When; }
  set { _When = value; }
}

What is the correct way to decorate DateTime properties for use with protobuf-net ?

BaltoStar
  • 8,165
  • 17
  • 59
  • 91

2 Answers2

5

It depends on what you want it to look like on the wire. If you want it to be a long (delta into epoch), then : do that. For example:

[ProtoMember(...)] public long Foo {get;set;}

If you want it to be a long on the wire and a DateTime in your code: do that:

 public DateTime Foo {get;set;}
 [ProtoMember(...)] private long FooSerialized {
    get { return DateTimeToLong(Foo); }
    set { Foo = LongToDateTime(value); }
  }

If you don't care and just want to store a DateTime, do that:

[ProtoMember(...)] public DateTime Foo {get;set;}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks Marc. Yes I need public property of type DateTime, so option 2 or 3 are advised. But I'm not understanding option 3 because proto2 doesn't support DateTime -- how is the DateTime represented on the wire ? – BaltoStar Sep 25 '16 at 01:09
  • @Balto see Bcl.Proto. basically, protobuf-net makes something up. If you need xplat: use the long trick (#2), IMO – Marc Gravell Sep 25 '16 at 06:12
  • I assume `DateTime` default value is `["1/1/0001 12:00:00 AM"]` = `DateTime.MinValue`. But what about `DateTime DataFormat` ? – BaltoStar Sep 27 '16 at 21:05
  • Also if go with option 2 how to implement `DateTime?` ? possibly with `long?` ? – BaltoStar Sep 27 '16 at 21:42
1

The Timestamp type is now supported:

[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"When",
    DataFormat = global::ProtoBuf.DataFormat.WellKnown)]
public DateTime When {get;set;}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900