Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to get default constructor of a Type

What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?

I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.

Type type = typeof(FooBar) BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; type.GetConstructors(flags)     .Where(constructor => constructor.GetParameters().Length == 0)     .First(); 
like image 318
Wes Haggard Avatar asked Sep 26 '08 22:09

Wes Haggard


People also ask

How do you find a default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

How many default constructors can a class have?

A default constructor is a constructor that is called without any arguments. It is not possible to have more than one default constructor.

Can you have multiple default constructors?

In C#, default constructor is nothing but a constructor which takes no parameter. So you cannot create a multiple constructor without any parameter which means you cannot have multiple default constructor, but you can have multiple constructor for a class.


2 Answers

type.GetConstructor(Type.EmptyTypes) 
like image 68
Curt Hagenlocher Avatar answered Oct 14 '22 10:10

Curt Hagenlocher


If you actually need the ConstructorInfo object, then see Curt Hagenlocher's answer.

On the other hand, if you're really just trying to create an object at run-time from a System.Type, see System.Activator.CreateInstance -- it's not just future-proofed (Activator handles more details than ConstructorInfo.Invoke), it's also much less ugly.

like image 28
Alex Lyman Avatar answered Oct 14 '22 08:10

Alex Lyman