Monday, August 07, 2006

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?

kick it on DotNetKicks.com

Saturday, October 14, 2006 7:44:53 AM (Central European Standard Time, UTC+01:00)
hi,
will you please elaborate on this with some code or picture...it would be helpfull if you provide some more information on this.
Mahesh kumar R
Tuesday, October 17, 2006 9:55:31 AM (Central European Standard Time, UTC+01:00)
What would you like me to elaborate on?
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview