Using an object created with Assembly.CreateInstance()

I am writing a C# application in which I need to load an assembly from a file and then create an instance of a specific type from that assembly. I'm using the following code to do this:

System.Reflection.Assembly a = System.Reflection.Assembly.LoadFile(path);
object myObject = a.CreateInstance("MyType");

The problem is that I then want to interact wth myObject as an instance of MyType:

MyType myInstance = myObject as MyType;

After this line of code myInstance is null. The VS debugger Autos pane shows the value of myObject as {MyType} and shows its Type as object {MyType}. Nonetheless, I cannot successfully cast myObject as MyType. Am I doing something wrong? Is there a way around this? Thanks.
Who is Participating?
I've only gotten this to work by using an interface to the class you want to create an instance of. Unfortunately, you have to put that interface into a separate assembly, and reference that assembly in your other 2 projects.

See the following question, maybe it will shed some light on your issue:

I hope this helps...

This version of CreateInstance works for me:
CreateInstance (
      string typeName,
      bool ignoreCase,
      BindingFlags bindingAttr,
      Binder binder,
      Object[] args,
      CultureInfo culture,
      Object[] activationAttributes

typeName needs to be fully qualified; i.e. YourNameSpace.YourClass
ignoreCase - I send false
bindingAttr = BindingFlags.CreateInstance
binder = null
args = an array of objects for the constructor - can be empty or null for the default constructor
culture = null - uses currentCulture
activationAttributes = null

Paracom_IncAuthor Commented:
I've tried that overload as well. The code is listed below. Line 6 fails because myInstance is null. Any ideas?

1         string path = @"C:\TestLibrary\bin\Debug\TestLibrary.dll";
2        System.Reflection.Assembly a = System.Reflection.Assembly.LoadFile(path);
3         string typeName = "TestLibrary.TestClass";
4         object myObject = a.CreateInstance(typeName);
5         TestLibrary.TestClass myInstance = myObject as TestLibrary.TestClass;
6         string s = myInstance.Hello();
Set a breakpoint on line 5 and see what you have in myObject.

Paracom_IncAuthor Commented:
Yes, the interface route is the way that I have done it as well. Thanks for the confirmation.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.