Is it possible to generate nullable members in protobuf-net?
message ProtoBuf1 {
optional Int32? databit = 1;
optional Nullable<bool> databool = 2;
}
Is it possible to generate nullable members in protobuf-net?
message ProtoBuf1 {
optional Int32? databit = 1;
optional Nullable<bool> databool = 2;
}
Yes, but it doesn't generate them by default if you are doing codegen from .proto.
If this is just C#, of course, you don't need a .proto - just:
If you are working from .proto, you could consider copying and editing
csharp.xslt
to suit your preferred layout.Here's my solution for nullable types when using Google's Protobuf .NET API which requires Protocol Buffers version 3. (Note that this is not using Marc Gravell's protobuf-net, so this isn't an exact answer to the question asked.)
In
NullableInt32.proto
:In
NullableInt32Extensions.cs
:This pattern can be used for any of the Protobuf non-length delimited scalar values—
double
,float
,int32
,int64
,uint32
,uint64
,sint32
,sint64
,fixed32
,fixed64
,sfixed32
,sfixed64
, andbool
.Here's how all of this works. Say you have a
Record
message that has aNullableInt32
field, and in this contrived example it's the only field.In
Record.proto
:Once this is compiled to C# with Google's
protoc.exe
, you can treat theId
property almost exactly like aNullable<int>
.Finally, let's look at how our
Record
message will be transfered over the wire with different values forId
.