I've always had the following question in my mind and couldn't find the question on SO:
How can I have my default constructor for Serialization/Activator purposes, while making sure a consumer is discouraged/disabled from using it?
In the past I've used hints like
///<summary>
/// Do not use the default constructor
///</summary>
which are obviously overlooked easily, unless you carefully hover and check every class you use.
While I would get better visual indication like this:
[Obsolete("Do not use the default constructor")]
it would be a complete abuse of the feature which leaves me shivering.
Is there any common way I'm not aware of to deal with this, or is it just me who feels annoyed by this in the first place?
If your class is within an class library, and the serialization happens from the class library itself, you can create an internal
wrapper class (deriving from your original class) that exposes the serialization constructor. In that way, you can make sure nothing from the outside is calling that constructor. With this approach, you have to use that wrapper type when deserializing.
That would still mean the constructor can be called from inside the class library of course, but it prevents most of the unintended use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With