Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 654
mafu Avatar asked Jan 13 '11 14:01

mafu


People also ask

What is a Parameterless constructor?

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.

Can constructors be Parameterless?

When a constructor is declared without any parameter or argument, then it is called a parameter-less constructor.

Does C# support Parameterless constructor?

The CLR allows value types to have parameterless constructors, but C# doesn't.


3 Answers

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);

like image 181
Alex J Avatar answered Oct 17 '22 21:10

Alex J


type.GetConstructor(Type.EmptyTypes) != null

would fail for structs. Better to extend it:

public static bool HasDefaultConstructor(this Type t)
{
    return t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null;
}

Succeeds since even enums have default parameterless constructor. Also slightly speeds up for value types since the reflection call is not made.

like image 17
nawfal Avatar answered Oct 17 '22 21:10

nawfal


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) ...
like image 13
Henk Holterman Avatar answered Oct 17 '22 21:10

Henk Holterman