12

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?

user664939
  • 1,977
  • 2
  • 20
  • 35
  • 1
    For it to be "safe" wouldn't he also have to check IsPublic and similar properties on the ConstructorInfo object returned by GetConstructor(). I don't know. I'm asking.. – Simen S Apr 06 '11 at 19:27

2 Answers2

13

Consider IsAbstract . It would handle abstract as well as static class. You may also want to check on IsInterface

WorldIsRound
  • 1,544
  • 10
  • 15
  • 1
    It seems that IsAbstract is returning true for interface as well: https://msdn.microsoft.com/en-us/library/system.type.isabstract(v=vs.110).aspx – Sauleil Mar 28 '18 at 14:20
  • Don't forget IsGenericTypeDefinition too! Can't create an instance of a generic type with unbound parameters. – IS4 Jan 11 '23 at 18:01
9

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536