Reputation: 2352
I want to use dynamic in C# to interact with objects defined in an external API (DLL). In such a way, I don't want to reference the API in my console app. Is this doable?
For instance, I used something as:
dynamic obj1 = new ObjectDefinedInAPI();
Compiler keeps on nagging that
The type or namespace name 'objectDefinedInAPI' could not be found ...
Any idea?
Thanks
Upvotes: 0
Views: 165
Reputation: 497
In addition to NeutronCode answer, you can also try the following:
public interface IDynamicService {
void DoSomething();
}
public void static main() {
var assembly = Assembly.LoadFrom("filepath");
var aClass = assembly.GetType("NameSpace.AClass");
IDynamicService instance = Activator.CreateInstance(aClass) as IDynamicService;
if (instance != null) {
instance.DoSomething();
}
}
This way you can ensure your type will have a specific implementation. Please note that the actual class must inherit the interface in order for this to work, so if you don't have access to the other dll source code, this won't help much. The upside of doing it this way is that you get Intellisense and will always be sure that your dynamic class interfaces well with your application.
Upvotes: 0
Reputation: 365
You can load the assembly manually and then create a instance of a class given that you know the assembly name and class name.
var assembly = Assembly.LoadFrom("filepath");
var aClass = assembly.GetType("NameSpace.AClass");
dynamic instance = Activator.CreateInstance(aClass);
Upvotes: 3