Link to home
Create AccountLog in
Avatar of Paracom_Inc

asked on

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.
Avatar of JimBrandley
Flag of United States of America image

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

Avatar of Paracom_Inc


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.

Avatar of jdbviper

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Yes, the interface route is the way that I have done it as well. Thanks for the confirmation.