views:

83

answers:

1

Hey guys.

I've been using Activator.CreateInstance() in some of my codes. But I was just wondering if there's any risk to making an instance using this?

+6  A: 

Well, there's the risk that your code is weakly typed, and you won't find out that you've accidentally tried to use it with a type which doesn't have a public parameterless constructor until execution time... and it's going to perform a bit worse than a direct constructor call. Other than that, it should be okay.

If you can design around it to use strongly typed factories instead, that would be preferable in various ways - but I totally understand that that's not always appropriate. Basically it should be a bit of a last recourse for when normal design patterns fail you, but it's a perfectly reasonable last recourse :)

Do you have any specific concerns?

Jon Skeet