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?
Decompiling
RuntimeType.InvokeMemberyields this fragment:In other words,
InvokeMemberwith thoseBindingFlagscallsActivator.CreateInstance. It goes through several more call layers (checking bindings, verifying arguments) before getting down to business.Activator.CreateInstance<T>is much more succinct:EDITED You might expect the latter to be faster, but a method called
RuntimeType.CreateInstanceSlowalso callsRuntimeTypeHandle.CreateInstanceto 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.