views:

58

answers:

3

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?

+1  A: 

You can't instantiate that class from outside it. Presumably it's been deliberately designed so that you can't instantiate it.

I'd expect there to be some static way of getting instances, such as a singleton property or a factory method... but if you need to be able to do this with any type, that's not going to work.

Basically, you'll need to rethink your design - don't try to subvert the wishes of the class author.

Jon Skeet
Is that for .Net classes in general or just Silverlight? However, while I agree that I wouldn't do this for instantiating classes in normal production code, my thinking has been that this should be ok if the tool I'm creating is used to instantiate simple poco objects to be used in unit tests. I'll add more detail about the class I'm trying to instantiate just in case that makes a difference.
mezoid
@mezoid: In general. If you start doing things that a class's author explicitly tried to stop you from doing, you're just *inviting* things to go wrong.
Jon Skeet
good point! so I should avoid using FormatterServices.GetUninitializedObject altogether then? What's the main usecase of that method? MSDN's description of it isn't very detailed...
mezoid
@mezoid: I believe it's mostly used internally for serialization. I would avoid it unless you've got a very specialized purpose such as serialization.
Jon Skeet
Thanks heaps for your answer Jon, it really helped me question my design. It turns out that (T)Activator.CreateInstance(typeof(T), true)was able to create the class I needed. See my answer below...
mezoid
@mezoid: I'm glad it worked for you, but it still feels a little smelly... I think I'd rather provide some sort of factory method on a per type basis. Obviously you know your context better though.
Jon Skeet
A: 

You can do it using reflection, but

  • you should really decide if you are doing the right thing. As others said the class is probably designed not to be instantiated that way. I understand however that in some rare cases this may be required.

  • you need to run this in full trust, i.e. out of the browser. You cannot do it inside the browser.

Here's the code:

var privateConstructors = typeof(MyClass).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var constr in privateConstructors)
{
    var obj = constr.Invoke(new object[0]);
    return;
}
throw new Exception("private constructor not found");
Francesco De Vittori
A: 

It turns out, that the answer was right in front of me.

If you have a class defined as follows:

public class MyClass
{
    private MyClass(){}
}

you can instantiate it using the following code which I mentioned in my question:

(T)Activator.CreateInstance(typeof(T), true)

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:

public MyClass()
{
    int a;
    private MyClass(int a)
    {
        this.a = a;
    }
}

However, it turns out there is a way suggested here to be able to instantiate this class:

int argA = 100; 
Type type = typeof(MyClass);

ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic 
| BindingFlags.Instance, null, new Type[] { typeof(int) }, null);

MyClass o = (MyClass)c.Invoke(new Object[] { argA });

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.

mezoid