Timestamp.proto problem in c#

3,101 views
Skip to first unread message

Uzair Saeed

unread,
Sep 9, 2016, 5:47:24 PM9/9/16
to Protocol Buffers
Hello,

I have successfully compiled my .proto file with google.proto.Timestamp and generated the .cs file with protoc. The only problem i am having is initialization in my c# code.

I have tried the following ,

.proto File

message teststamp{

string Name = 1 ;
string address = 2;
google.protobuf.Timestamp _timeStamp = 3;
}


C# File

teststamp test = new teststamp();

test.Name = "Test";
test.address = "Test_Test_TEST"
//Example 2 : POSIX
test._timeStamp.Seconds = DateTime.Now.Second;
test._timeStamp.Nanos = DateTime.Now.Second*1000 ;


The above is compiling without errors but giving me this error "Object reference not set to an instance of an object" .I have tried few other approaches but due to less help it is unable to fix the error. 

Please help me out in this issue

Thanks

Jon Skeet

unread,
Sep 10, 2016, 11:28:57 AM9/10/16
to Protocol Buffers
Timestamp is just a regular class - so you need to create a new instance before setting properties, e.g.

// Don't actually use this - see below.
test._timeStamp = new Timestamp
{
    Seconds = DateTime.Now.Second,
    Nanos = DateTime.Now.Second * 100
};

However, there are various things wrong with this:
- That will only give you a Seconds value in the range 0-59
- You're evaluating DateTime.Now twice, so you could get different values
- You're using DateTime.Now which is a *local* time; Timestamp is for global timestamps

Fortunately, there's a factory method to make all of this easy:

test._timeStamp = Timestamp.FromDateTime(DateTime.UtcNow);
Reply all
Reply to author
Forward
0 new messages