04 November, 2012

De-serialize to class with private or no empty constructor

When transferring DTO objects around in .NET sometimes you need to deserialize data to an object with no or private/internal empty constructors. What I have normally done is adding a public empty constructor to my own classes that just does nothing, but I always deemed it as an ugly hack, and have marked them all with TODO comments in the code...

Today I stumbled upon a this method in .NET FormatterServices.GetUninitializedObject that actually can instantiate a class without using any of the constructors in the class. The best part is that it works in all .NET versions, because we are targeting our DTO objects for .NET Framework 2.0 to ensure compatibility with all our clients.

I found these detailed guides about using the method:
http://www.rvenables.com/2009/08/instantiating-classes-with-internal-constructors/
http://mikeoff.blogspot.dk/2006/07/creating-object-instance-without.html

No comments:

Post a Comment