Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict usage of parameterless constructor to serialization/Activator/new()

Tags:

c#

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?

like image 525
Dbl Avatar asked May 09 '16 08:05

Dbl


1 Answers

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.

like image 69
Patrick Hofman Avatar answered Nov 04 '22 16:11

Patrick Hofman