DEV Community

Cover image for protobuf in C#
Jayesh Tanna
Jayesh Tanna

Posted on

protobuf in C#

Protobuf is used to serialized data structure efficiently. It is faster, smaller & simpler than XML. Protobuf is useful in developing programs to communicate with each other over a wire and it is created by Google. It help us in creating micro services. Protobuf is not an object oriented language so it does not support feature like inheritance. We need to define our data structure once and then we need to use auto generated code which will be used for read and write data to different sources. Protobuf is available in all programming languages like Go, python, C#, Java etc.

Protobuf supports most of the all data types like string, int32, double, float, bool, maps etc. Protobuf also supports enum similar like c#, Java.

Lets create a simple example of protobuf in c# language using visual studio.

  1. Create .net core console application.
  2. Add these nuget packages to your project: Core, Core.Tools and Google.Protobuf
  3. Right click on the project and add a new file named "Person.proto"
  4. Add below lines of code in "Person.proto" file

syntax = "proto3";
option csharp_namespace = "CalculatorService.Generated";
message Person
{
int32 id = 1;
string name = 2;
Address address = 3;
}

message Address
{
int32 id = 1;
string addressLine1 = 2;
string city = 3;
}

proto3 is the syntax version of proto file. If we don't specify this then by default it will consider proto2 as syntax version.
csharp_namespace is an optional line. When code will be generated by proto3 compiler, then all classes will be created under this namespace.
message Person and Address both are different types of data structures. When code will be generated by protobuf compiler, two different classes will be created Person and Address. Both will have respected fields id, name, Address and Id, AddressLine1 and city.
We always need to assign unique identifier to each field. Reason for providing unique identifier is that when compiler will serialize or deserialize  any field, then it will be based on this unique identifier so serialization and deserialization will be faster.

  1. Right click on the proto file and click on Properties. Choose "Protobuf compiler" from build action's options. By setting this property, your proto file will be compiled by protobuf compiler. If you have not installed above specified nuget packages, then you won't be able to see "protobuf compiler" option.
  2. Build the solution.
  3. After successful build, open obj/debug/netcoreapp/Message.cs. This code is auto generated by protobuf compiler.

Congratulations! you have just created new protobuf classes.

Top comments (0)