How do I check if a type provides a parameterless constructor?

mafu picture mafu · Jan 13, 2011 · Viewed 28.7k times · Source

I'd like to check if a type that is known at runtime provides a parameterless constructor. The Type class did not yield anything promising, so I'm assuming I have to use reflection?

Answer

Alex J picture Alex J · Jan 13, 2011

The Type class is reflection. You can do:

Type theType = myobject.GetType(); // if you have an instance
// or
Type theType = typeof(MyObject); // if you know the type

var constructor = theType.GetConstructor(Type.EmptyTypes);

It will return null if a parameterless constructor does not exist.


If you also want to find private constructors, use the slightly longer:

var constructor = theType.GetConstructor(
  BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, 
  null, Type.EmptyTypes, null);

There's a caveat for value types, which aren't allowed to have a default constructor. You can check if you have a value type using the Type.IsValueType property, and create instances using Activator.CreateInstance(Type);