wildquaker
wildquaker

Reputation: 41

Activator.CreateInstance()

I've been using Activator.CreateInstance() in some of my codes. Is there any risk to making an instance using this?

Upvotes: 4

Views: 945

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503120

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?

Upvotes: 12

Related Questions