Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protobuf-net : how to represent DateTime in C#?

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 ?

like image 547
BaltoStar Avatar asked Sep 24 '16 01:09

BaltoStar


1 Answers

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;}
like image 145
Marc Gravell Avatar answered Sep 28 '22 05:09

Marc Gravell