How to initialise a class without calling the constructor (.Net)

Sometimes we want to test some really nasty legacy code but are inhibited by constructors taking tricky things like HttpWhatevers, God objects and so on which you do not care about but would require enormous effort setting up just to try and get an instance of the damn thing so you can test your method.

One way out is to create a parameterless constructor on the class which is only used for testing. Not at all nice, but sometimes necessary to create that first seam.

A candidate I was pair interviewing with introduced me to something which may prove preferable in these cases – the Microsoft serialization library has a method which will initialize a class without calling the constructor:

FormatterServices.GetSafeUninitializedObject
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getsafeuninitializedobject.aspx

This way you don’t have to modify the code!

I would only ever advise using this if your only other sensible option would be to override the constructor. Hopefully once you have your tests you would be able to confidently refactor out the problematic code.

One thought on “How to initialise a class without calling the constructor (.Net)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>