C# – 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?

Best Solution

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.