silentorbit / protobuf

C# code generator for reading and writing the protocol buffers format
https://silentorbit.com/protobuf/
MIT License
307 stars 105 forks source link

Have message classes use common Interface? #42

Closed zeroZshadow closed 2 years ago

zeroZshadow commented 9 years ago

Atm all messages use partial classes to get functions such as Serialize, but this makes it impossible to use something like a generic type constraint. Wouldn't it be preferable to have all Message classes implement a common Interface?

An example of why this would be usefull:

void SendMessage<T>(UInt32 messageType, T message) where T: IProtoMessage {
  using (MemoryStream stream = new MemoryStream()) {
      // Prefix header to actual message
      using (BinaryWriter writer = new BinaryWriter(stream)) {
        writer.Write(messageType);

        // Actual message
        T.Serialize(stream, message);
        websocket.Send(stream.ToArray());
      }
    }
}

As far as I know this isnt currently possible.

hultqvist commented 9 years ago

I don't see how the use of partial is a constraint, you can today write your own addition to a generated class like this.

partial class Foo : IProtoMessage { }

And write your own IProtoMessage interface matching the current one for generated messages.

But I agree that the above can easily be integrated into the generator.

hultqvist commented 9 years ago

Although you could have a static Serialize of the interface the inner code in your example would look like this:

    // Actual message
    message.Serialize(stream);
    websocket.Send(stream.ToArray());
zeroZshadow commented 9 years ago

Yes i realized that interfaces cant have static functions (I'm still a little new to them) It was just an example, the main issue is that dealing with serializing messages now takes a lot of duplicated code, or wierd workarounds.