Protobuf In C#

Protobuf is useful in developing programs to communicate with each other over a wire and it is created by Google.

Protobuf is used to serialize 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 helps us in creating gRPC services. Protobuf is not an object oriented language so it does not support features like inheritance. We need to define our data structure once and then we need to use auto generated code which will be used to 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 data types like string, int32, double, float, bool, maps, etc. Protobuf also supports enum similar like c#, Java.
Let's create a simple example of protobuf in C# language using Visual Studio.
  • Create .net core console application.
  • Add these nuget packages to your project: Core, Core.Tools and Google.Protobuf
  • Right click on the project and add a new file named "Person.proto"
  • Add the below lines of code in "Person.proto" file
    1. syntax = "proto3";  
    2. option csharp_namespace = "CalculatorService.Generated";  
    3. message Person  
    4. {  
    5.    int32 id = 1;  
    6.    string name = 2;  
    7.    Address address = 3;  
    8. }  
    10. message Address  
    11. {  
    12.    int32 id = 1;  
    13.    string addressLine1 = 2;  
    14.    string city = 3;  
    15. }  
    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 respective field's 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.

  • 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 the above specified nuget packages, then you won't be able to see "protobuf compiler" option.

  • Build the solution.

  • After a successful build, open obj/debug/netcoreapp/Message.cs. This code is auto generated by protobuf compiler.
Congratulations! You have just created new protobuf classes.