Reputation: 7213
Assembly assembly = Assembly.GetCallingAssembly();
assembly.CreateInstance("MyType");
and
Activator.CreateInstance(typeof(MyType));
Ok, the Activator.CreateInstance can be generic which eliminates the need to cast your created instance, but when would you use one against the other?
Upvotes: 1
Views: 138
Reputation:
In the first instance you could use that methodology to create an instance dynamically without knowing the type at run time. Where as the second one you need to know the type when you're writing the code.
Upvotes: 2
Reputation: 75862
An obvious "problem" is that the former is stringly typed which is rarely a good thing, but it has the situational advantage of being runtime type checked so you have a level of dynamism. Personally, the refactor-factor outweighs dynamic design concerns mostly.
Upvotes: 2
Reputation: 1063609
The string-based version looks only in the root namespace (since no namespace is included) of the current assembly (since no assembly name is included), plus a few system assemblies. The Type-based version already knows the type to use, so no search is necessary. It could be in any namespace or assembly, but the implication of typeof is that you could also have used "new".
The Type approach makes more sense when you will have a Type supplied at runtime, but not usually that close to the object creation.
Upvotes: 2