Thursday, August 5, 2010

C#: How to check if a type has a default/parameterless constructor

The following C# snippet returns true if the passed in type has a default/parameterless constructor:


public bool HasDefaultConstructor(Type type)
{
 if (type.IsValueType)
  return true;

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

 if (constructor == null)
  return false;

 return true;
}