Search code examples
protobuf-netderived-types

How does deriving work in protobuf-net?


Like I would do in C#:

class DerivedClass : BaseClass {}

is there a way to recreate this behaviour with messages in a proto-file? So that the DerivedClass is of type BaseClass and can inherit its properties.

I tried to extend my base message, but this yields a different result.


Solution

  • If we assume that this is:

    [ProtoContract]
    [ProtoInclude(7, typeof(DerivedClass))]
    public class BaseClass {}
    
    [ProtoContract]
    public class DerivedClass : BaseClass {}
    

    Then we can use:

    string proto = Serializer.GetProto<BaseClass>();
    

    to see how protobuf-net is interpreting it:

    message BaseClass {
       // the following represent sub-types; at most 1 should have a value
       optional DerivedClass DerivedClass = 7;
    }
    message DerivedClass {
    }
    

    This would actually map fairly well to the new oneof - simply, GetProto hasn't been updated to use the new syntax (it wouldn't impact the output, though). But the following would also be equivalent:

    message BaseClass {
        oneof subtypes {
            // the following represent sub-types; at most 1 should have a value
            DerivedClass DerivedClass = 7;
            AnotherDerivedClass AnotherDerivedClass = 8;
            AndOneMoreForLuck AndOneMoreForLuck = 9;
        }
    }
    message DerivedClass {
    }
    message AnotherDerivedClass {
    }
    message AndOneMoreForLuck {
    }