views:

630

answers:

2

Forgive me if this question has already been asked and answered.

Given a class of type T, what is the difference between the following?

T myObj = Activator.CreateInstance<T>();

T myObj = typeof(T).InvokeMember(null, BindingFlags.CreateInstance, null, null, null);

Is one solution preferred over the other?

+6  A: 

Decompiling RuntimeType.InvokeMember yields this fragment:

if ((bindingFlags & BindingFlags.CreateInstance) != BindingFlags.Default)
{
    if (((bindingFlags & BindingFlags.CreateInstance) != BindingFlags.Default) && ((bindingFlags & (BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.SetField | BindingFlags.GetField | BindingFlags.InvokeMethod)) != BindingFlags.Default))
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"), "bindingFlags");
    }
    return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}

In other words, InvokeMember with those BindingFlags calls Activator.CreateInstance. It goes through several more call layers (checking bindings, verifying arguments) before getting down to business. Activator.CreateInstance<T> is much more succinct:

public static T CreateInstance<T>()
{
    bool bNeedSecurityCheck = true;
    bool canBeCached = false;
    RuntimeMethodHandle emptyHandle = RuntimeMethodHandle.EmptyHandle;
    return (T) RuntimeTypeHandle.CreateInstance(typeof(T) as RuntimeType, true, true, ref canBeCached, ref emptyHandle, ref bNeedSecurityCheck);
}

EDITED You might expect the latter to be faster, but a method called RuntimeType.CreateInstanceSlow also calls RuntimeTypeHandle.CreateInstance to do the work; it's used as a fallback if an Activator cache entry for the constructor can't be found. I'd do some performance testing if you're looking for the fastest solution of the two.

Ben M
@Ben M: Thanks so much!
Matt Davis
A: 

What version of .NET containing RuntimeMethodHandle.EmptyHandle? I am using .NET 3.5 and Visual studio 2008. It gives the error "EmptyHandle type name does not exist in the type System.RuntimeMethodHandle".

Then I used "RuntimeMethodHandle emptyHandle = new RuntimeMethodHandle();". Another error presents. RuntimeTypeHandle does not have a CreateInstance method either. Activator has. But it does not take any ref parameter.

Thanks for clarification in advance!

Don
If you've got a question post it as such, not as an answer to someone else's question.
ChrisF