FranzHuber23
FranzHuber23

Reputation: 4252

C# ProtoBuf inheritance with generics

Imagine the following code example:

[ProtoContract]
[ProtoInclude(1, typeof(ExampleState))]
public abstract class BaseState<T>
{
    [ProtoMember(2)]
    public T Model { get; set; }

    [ProtoMember(3)]
    public string Id => this.Model.Id;
}

[ProtoContract]
public class ExampleState: BaseState<ExampleModel>
{
    [ProtoMember(1)]
    public DateTimeOffset LastSeenAt { get; set; }
}

[ProtoContract]
public class ExampleModel
{
    [ProtoMember(1)]
    public DateTimeOffset CreatedAt { get; set; }

    [ProtoMember(2)]
    public string Name { get; set; }
}

when using protobuf-net. The BaseState<T> defines some ProtoInclude for ExampleState, but then the warning PBN0012: The type 'ExampleState' is declared as an include, but is not a direct sub-type is shown.

Is this desired behaviour or a bug? How does a workaround look like without having to re-write all models (In our case, this could get pretty complicated).

Upvotes: 1

Views: 199

Answers (1)

Stan1k
Stan1k

Reputation: 360

We had a similar issue and found a solution/example on GitHub

In short, you need an abstract base class using this example syntax:

[ProtoContract]
[ProtoInclude(1, typeof(ResBase<int>), DataFormat = DataFormat.Group)]
[ProtoInclude(2, typeof(ResBase<string>), DataFormat = DataFormat.Group)]
public abstract class ResBase {}

Upvotes: 0

Related Questions