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();
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() .
A default constructor is a constructor that is called without any arguments. It is not possible to have more than one default constructor.
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.
type.GetConstructor(Type.EmptyTypes)
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.
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