Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Protobuf-Net with a class without a parameterless constructor?

Using Protobuf-Net, I see that it does not seem possible to deserialize a class without having a parameterless constructor or I may be missing something?

I don't want some of the classes with a parameterless constructor. Is there some kind of attributes that I could use or some other technique?

like image 654
Stécy Avatar asked Aug 26 '09 15:08

Stécy


2 Answers

protobuf-net depends currently on having a parameterless constructor to work.

However that constructor need not be public (it will use reflection if need be to invoke it) so you may be able to define the required private constructor just for use by protobuf-net (adding a comment as to why) and deal with specific serialization related issues there.

This keeps the rest of your api from being able to construct 'illegal' instances.

Marc points out that if you are talking about the outermost message object, you could also create the object yourself and call Serializer.Merge. But if it needs to create an object (because it currently has a null instance, or for new items in a list/array), then it looks for a default constructor.

like image 185
ShuggyCoUk Avatar answered Oct 12 '22 06:10

ShuggyCoUk


ShuggyCoUk is right about it using the parameterless constructor.

Just for completeness, though - if you are talking about the outermost message object, you could also create the object yourself and call Serializer.Merge. But if it needs to create an object (because it currently has a null instance, or for new items in a list/array), then it looks for a default constructor.

I suppose that I could also provide some markup in the attribute to say "just create a raw object via FormatterServices", but this feels unnecessary (compared with a private parameterless constructor), and may not work on all platforms (Silverlight, CF, etc - being likely problems).

like image 22
Marc Gravell Avatar answered Oct 12 '22 06:10

Marc Gravell