It was difficult for me to fulfill some of the answers here because I was trying to instantiate an object from another assembly (but in the same solution). Therefore, I thought I would publish what I found to work.
First, the Activator.CreateInstance method has several overloads. If you simply call Activator.CreateInstance(Type.GetType("MyObj")) , this assumes that the object is defined in the current assembly, and it returns MyObj .
If you answer as indicated in the answers here: Activator.CreateInstance(string AssemblyName, string FullyQualifiedObjectName) , it 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 another assembly (BTW, you can use this overload in the current assembly, just leave the AssemblyName parameter null).
Now I found that the suggestion typeof(ParentNamespace.ChildNamespace.MyObject).AssemblyQualifiedName for AssemblyName suggested above really gave me errors, and I could not get this to work. I would get a System.IO.FileLoadException (could not load the file or assembly ...).
What I got works as follows:
var container = Activator.CreateInstance(@"AssemblyName",@"ParentNamespace.ChildNamespace.MyObject"); MyObject obj = (MyObject)container.Unwrap(); obj.DoStuff();
Kevin Fichter Apr 02 '17 at 22:58 on 2017-04-02 22:58
source share