I had some difficulty implementing some of the answers here because I was trying to instantiate an object from a different assembly (but in the same solution). So I thought I'd post what I found to work.
First, the Activator.CreateInstance
method has several overloads. If you just call Activator.CreateInstance(Type.GetType("MyObj"))
, that assumes the object is defined in the current assembly, and it returns a MyObj
.
If you call it as recommended in the answers here: Activator.CreateInstance(string AssemblyName, string FullyQualifiedObjectName)
, then it instead returns an ObjectHandle
, and you need to call Unwrap()
on it to get your object. This overload is useful when trying to call a method defined in a different assembly (BTW, you can use this overload in the current assembly, just leave the AssemblyName
parameter null).
Now, I found that the suggestion above to use typeof(ParentNamespace.ChildNamespace.MyObject).AssemblyQualifiedName
for AssemblyName
actually gave me errors, and I could not get that to work. I'd get System.IO.FileLoadException
(could not load file or assembly...).
What I did get to work is as follows:
var container = Activator.CreateInstance(@"AssemblyName",@"ParentNamespace.ChildNamespace.MyObject");
MyObject obj = (MyObject)container.Unwrap();
obj.DoStuff();