12

I'm encountering this Exception in my project using Protobuf.net:

InvalidOperationException "Unexpected sub-type: foo"

I have a class which I'm sending which looks like this:

class message
{
    list<bar> listOfBars;
}

foo inherits off bar, However protobuf seems to choke on this and generate the exception above. Is there some way around this? I need to be able to hold all different subtypes of bar in the list, so a more type constrained solution would be difficult/impossible.

Martin
  • 12,469
  • 13
  • 64
  • 128

2 Answers2

19

I may be mistaken, but I think you need to specify on the inherited class which subtypes inherit from it, for example:

[Serializable, ProtoContract, ProtoInclude(100, typeof(Foo))]
class Bar { }

[Serializable, ProtoContract]
class Foo : Bar { } // Inherits from Bar
djdd87
  • 67,346
  • 27
  • 156
  • 195
  • I'll try that, it will take a while because Bar and foo are in different projects. I guess I'll have to fiddle around the dependancies a little :/ – Martin Sep 26 '10 at 11:56
  • 1
    @Martin @GenericTypeTea good answer; minor note -the [Serializable] isn't needed (but does no harm either) – Marc Gravell Sep 27 '10 at 22:29
  • 6
    Doesn't that violate the open-closed principle? I mean, every time you add another subclass, you will need to modify the base class(the include attribute)? Also, the base class and subclasses need to be in the same assembly to avoid circular dependencies. Is there another way arround this? Maybe setting up the protobuf model manualy (any docs on this)? – anakic Sep 06 '12 at 13:46
  • 4
    @AntonioNakicAlfirevic: I'm sure you've already found out about this, but for anyone else who comes across this: http://stackoverflow.com/questions/6247513/protobuf-net-inheritance – RenniePet Sep 03 '13 at 05:19
  • @RenniePet: Yepp, that's the approach I ended up successfully using. – anakic Sep 09 '13 at 17:23
0

I'm not 100% on protocol buffers, and maybe I'm way off base here but are you thinking that List is assignable from List where Bar inherits from Foo? This is not the case - they are considered two different types with no relation. In .NET 4, covariant Type parameters are supported but it requires support from the collection (which List does not offer even in .NET 4, as this would be a breaking change - arguably older code that attempts this is broken anyway, but it's still a change in behaviour)

x0n
  • 51,312
  • 7
  • 89
  • 111