I want to load a type at run time using reflection. Below are the steps:
- Load the assembly using
Assembly.LoadFile(assemblyPath); - Use the
GetTypemethod to obtain the type - Use
Activator.CreateInstanceto create the instance of type.
Below is my code:
Assembly assembly = Assembly.LoadFile(assemblyName);
Type type = assembly.GetType("RomanConerter.Converter");
object obj = Activator.CreateInstance(type);
Problem I am facing is with the last line. My Converter has one method name Add. But I cannot access this method using obj.
Note: The assembly which I am trying to load in in other project, and I have hasrd coded the path.
Can anyone help me out please ?
This all depends on whether the type
RomanConverter.Converteris available to you in your calling application (i.e. that contains the code you’ve posted). If so, then you just cast.If not – then you can late-bind the method with reflection (as others have said) or use
dynamic, but imho you’d do better to use a common base or interface:(I’m guessing the signature here)
And then change this plug-in type of yours to:
Now when you get the object from
Activator.CreateInstanceyou just cast toICanAdd:Now you can call the method.