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?
A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.
When a constructor is declared without any parameter or argument, then it is called a parameter-less constructor.
The CLR allows value types to have parameterless constructors, but C# doesn't.
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)
;
type.GetConstructor(Type.EmptyTypes) != null
would fail for struct
s. Better to extend it:
public static bool HasDefaultConstructor(this Type t)
{
return t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null;
}
Succeeds since even enum
s have default parameterless constructor. Also slightly speeds up for value types since the reflection call is not made.
Yes, you have to use Reflection. But you already do that when you use GetType()
Something like:
var t = x.GetType();
var c = t.GetConstructor(new Type[0]);
if (c != null) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With