views:

1319

answers:

3

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();
+18  A: 
type.GetConstructor(Type.EmptyTypes)
Curt Hagenlocher
the static members you just never look at... this is awesome.
Darren Kopp
Private members are not looked at either. Assuming you only need public then this does appear to be the simplest. However is it the fastest? I'm working on a test right now to find out.
Wes Haggard
After some measuring this approach vs my approach using MeasureIt (http://msdn.microsoft.com/en-us/magazine/cc500596.aspx) this approach is faster in all but the simplest cases and even then it is barely slower. So this is both the simplest and the fastest. Thanks!
Wes Haggard
+4  A: 

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.

Alex Lyman
A: 

you would want to try FormatterServices.GetUninitializedObject(Type) this one is better than Activator.CreateInstance

However , this method doesn't call the object constructor , so if you are setting initial values there, this won't work Check MSDN for this thing http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx

there is another way here http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx

however this one fails if the object have parametrize constructors

Hope this helps

Mohamed Faramawi