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.
System.Reflection.Assembly
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.
ASKER
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 \TestLibra ry.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();
1 string path = @"C:\TestLibrary\bin\Debug
2 System.Reflection.Assembly
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.
Jim
Jim
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yes, the interface route is the way that I have done it as well. Thanks for the confirmation.
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.CreateInstanc
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
Jim