In C#, how can I find out if a Type
can be instantiated? I am trying to avoid an Activator.CreateInstance exception.
My current method is type.IsClass && !type.IsInterface
, but I am worried this could fail on abstract classes, etc. I also considered checking type.TypeInitializer == null
, but I am not sure if that is foolproof either.
What is the simplest/most efficient way possible to find out if a Type
is instantiable?
Consider IsAbstract . It would handle abstract as well as static class. You may also want to check on IsInterface
There are many other traps. It could have a constructor that is private or protected. Or it might not have a default constructor, only constructors that take certain argument types. If you have to worry about that then you are surely using Activator.CreateInstance() when it should not be used. Just arbitrarily constructing objects can only create havoc, you have no idea what kind of side effects they may have. Avoid the "FormatDisk" class.
An exception is your friend, it tells you that your assumptions were wrong. Never intentionally stop the .NET framework from being helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With