protocol-buffersproto3protocol-buffers-3

Protobuff package vs option csharp_namespace


I am creating a gRPC service using Proto 3 and C#.

In the Google developer guide for Protobuff it says about package:

In C# the package is used as the namespace after converting to PascalCase, unless you explicitly provide an option csharp_namespace in your .proto file.

So I'm not sure from that what's the difference between package and option csharp_namespace? What happens if I declare them both? If I declare one of them then is the other one redundant?


Solution

  • Packages are quite confusing in Protocol Buffers since people don't really see Protobuf as a language by itself. The protobuf package is useful for generation in your case (when you don't define csharp_namespace), but this is also useful within your proto files.

    If you have:

    a.proto

    syntax = "proto3";
    
    package my_package;
    
    message A {}
    

    in one file and you import this file in another which doesn't use the package, as so:

    b.proto

    syntax = "proto3";
    
    import "a.proto";
    
    message B {
      my_package.A a = 1;
    }
    

    you will need to specify the fully qualified name (my_package.A).

    Now, for option csharp_namespace. This will tweak the code generation and so that the namespace in your C# code is the one that you provided as value. So, as for which one will prevail if you define both, it should be the option one since this is for tweaking the generation, where the package is more for you protobuf architecture.