For a long time I have been in need of a mechanism that allows me to create an instance of an object without calling any of its constructors like the Activator.CreateInstance does. All this time I have also been aware of the fact that it can be done. My motives weren't strong enough to dig dipper in to the problem, though. Until recently...
On my recent project I have enforced the use of a factory pattern for creating each object so for example to create a Document object we use something like Document.CreateDocument(). To enforce the use of this method, all classes should have a no public constructors declared. So it worked that way for some time now. Recently I have been forced to make some changes to the code and I have found the public parameterless construcor on the class that I have been modifying. A quick scope change to private and no compiler errors - good I thought. But..
Then came the runtime exceptions :-(. A quick memory refresher to remind me that the reason the public parameterless constructor is there lies in the parts of the code which use the late binding mechanisms of Reflection such as Activator.CreateInstance which throws errors in the runtime. I have used this mechanism in MyObjectDataSource control to create objects for insertion. Another place was a simple in house data mapper.
Now my motivation has been upgraded to a level that pushed me to make some investigation and after a while I've found the solution: FormatterServices.GetUninitializedObject. This thingy creates your objects without calling any constructor. Sweet! No more problems for me.
I have also checked the performance of this kind of instantiation and it is very good, much faster than Activator.CreateInstance. The only drawback is that any logic from the constructors is not invoked, but that is not a major issue for me since mostly the objects construced in such a way are data transfer objects. I also wonder WHY Microsoft controls such as ObjectDataSource does not use this technique but forces you to have the parameterless construcor?