I’m working on a feature request for a .NET test data builder. I need to be able to instantiate classes that only have private parameterless constructors.
For instance, I might need to instantiate the following class:
public class MyClass()
{
private MyClass(){}
}
For most other classes I use the following code:
(T)Activator.CreateInstance(typeof(T), true)
But for classes that only have a private parameterless constructor I use the following:
(T)FormatterServices.GetUninitializedObject(typeof(T))
Unfortunately, I also have the requirement that this work in Silverlight and unfortunately Silverlight doesn’t currently contain System.Runtime.Serialization.FormatterServices.
Does anyone know of anything in the Silverlight implementation that would allow me to get around this? Failing that, does anyone know how I might implement my own version of this method?
It turns out, that the answer was right in front of me.
If you have a class defined as follows:
you can instantiate it using the following code which I mentioned in my question:
The additional parameter of true, creates an instance using the type’s default constructor.
So it turns out, I didn’t even need to use FormatterServices.GetUninitializedObject in the first place.
However, I’d like to thank Jon Skeet for his answer because it helped me to question my design and dig a bit deeper into Activator.CreateInstance and increase my understanding of class instantiation a little.
For now, my solution is remove the use of FormatterServices and just allow an exception to be thrown if something goes wrong with the type creation.
Currently, from what I can tell, using (T)Activator.CreateInstance(typeof(T), true) I should be able to construct most classes I’ve come across except for the following:
However, it turns out there is a way suggested here to be able to instantiate this class:
But after thinking about what Jon said, I don’t think this will be of much use to anyone using the test data builder I’m enhancing. If someone’s gone to that much trouble to prevent a class from being instantiated, then perhaps it shouldn’t be able to be constructed other than by the means provided by the class designer.