I have type T
and I'd like to check if its safe to pass to Activator.CreateInstance(T)
.
What comes to my mind is to do this:
if(!T.IsInterface && !T.IsAbstract)
{
instance = (T)Activator.CreateInstance(T);
}
BUT:
- Is this enough? Did I not miss a necessary test? Is it possible that a type is not an interface and is not an abstract class but nevertheless still cannot be instantiated? Given my knowledge of C# is still quite rudimentary I think it's very possible I missed a corner case or two.
- Do I have to write a test manually? Is there not something like
T.IsInstantiable
or whatever included in the language?
EDIT: No, T
is not coming from a generic constraint. This is the piece of code T
is coming from:
var instances = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.Where(
// some other constraints
).Where(
// can be instantiated, I'm trying to figure this part in my question
).Select(
T => Activator.CreateInstance(T)
);