pquest
pquest

Reputation: 3290

Can Nullable types be sent through Protocol Buffers?

The Proto3 C# Reference contains the following text:

Wrapper Type Fields

Most of the well-known types in proto3 do not affect code generation, but the wrapper types (StringWrapper, Int32Wrapper etc) change the type and behaviour of the properties.

All of the wrapper types that correspond to C# value types (Int32Wrapper, DoubleWrapper, BoolWrapper etc) are mapped to Nullable<T> where T is the corresponding non-nullable type. For example, a field of type DoubleValue results in a C# property of type Nullable<double>.

Fields of type StringWrapper or BytesWrapper result in C# properties of type string and ByteString being generated, but with a default value of null, and allowing null to be set as the property value.

For all wrapper types, null values are not permitted in a repeated field, but are permitted as the values for map entries.

When trying to generate a .cs file from a .proto file, If I try to declare a field as Int32Wrapper in the .proto file, protoc.exe throws an error about Int32Wrapper not existing.

syntax ="proto3";
package prototest;
import "MessageIdentifier.proto";


message TestMessage {
    string messageTest = 1;
    fixed64 messageTimestampTicks = 2;
    uint32 sequenceNumber = 3;
    MessageUniqueID uniqueID = 4;
    Int32Wrapper nullableInt = 5; 
}

It seems there is some additional step that is missing here, does anyone know how to enable these types?

Upvotes: 25

Views: 34305

Answers (2)

zetroot
zetroot

Reputation: 630

I will try to improve Nick's answer as it hasn't helped me. grpc compiler claimed that he has no information on google.protobuf.Int32Wrapper type. I have found it is actually called google.protobuf.Int32Value, though google calls it Int32Wrapper in the docs. So the code that helped me was the following:

...
import "google/protobuf/wrappers.proto";
...
message TestMessage {
    ...
    google.protobuf.Int32Value nullableInt = 5; 
}

Other links:

Upvotes: 36

Nick Randell
Nick Randell

Reputation: 18295

In respect that https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/wrappers.proto

You need to import google/protobuf/wrappers.proto in order for this to work.

syntax ="proto3";
package prototest;
import "MessageIdentifier.proto";
import "google/protobuf/wrappers.proto";

message TestMessage {
    string messageTest = 1;
    fixed64 messageTimestampTicks = 2;
    uint32 sequenceNumber = 3;
    MessageUniqueID uniqueID = 4;
    google.protobuf.Int32Value nullableInt = 5; 
}

You can then use it as an int? ,eg nullableInt.HasValue and nullableInt.Value

Upvotes: 11

Related Questions