Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if type is instantiable

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?

like image 722
user664939 Avatar asked Apr 06 '11 19:04

user664939


2 Answers

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

like image 83
WorldIsRound Avatar answered Oct 14 '22 10:10

WorldIsRound


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.

like image 21
Hans Passant Avatar answered Oct 14 '22 09:10

Hans Passant