Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance()

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

like image 820
wildquaker Avatar asked Dec 17 '22 05:12

wildquaker


1 Answers

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?

like image 107
Jon Skeet Avatar answered Jan 06 '23 21:01

Jon Skeet