I am using an 3rd party assembly that provides services via a static class:
Foo.Bar.StaticLibraryClass.Start();
var x = Foo.Bar.StaticLibraryClass.GetSomeStuff();
Foo.Bar.StaticLibraryClass.Stop();
If the class were not static, I could use an instance of it via a dynamically typed variable:
dynamic lib = new Foo.Bar.NotStaticLibraryClass();
lib.Start();
var x = lib.GetSomeStuff();
lib.Stop();
Unfortunately however, the class IS static. Is there any equivalent I can write that will let me work in the same way?
dynamic lib = /* ??????? */
lib.Start();
var x = lib.GetSomeStuff();
lib.Stop();
(Why do I want to use a dynamic variable to access a perfectly good .NET type? There are actually multiple versions of the library DLL, and I must identify and load the appropriate one at runtime. The different DLLs expose the same type and method names, but they do inherit from any common interface. So if I can find a way to use dynamic typing, it will spare me from writing a lot of fiddly reflection code to use the DLLs’ methods.)
Sorry, C# dynamic does not support this usage directly. In order to call a class method in C#, you have to name the type in your source code directly. And to do that, you have to reference the assembly. dynamic doesn’t change this.
dynamic does dispatch to class methods when necessary (such as when you have a dynamic argument), but even in those cases the limitation above stands.
If the target types provided an instance that you could put in a dynamic variable, then you’d be fine. If you provided such an instance you’d be fine. Alternatively, if you have your heart set on dynamic, you could write your own IDynamicMetaObjectProvider that wraps these class methods dynamically given a System.Type. That would be an instructive project if you want to learn about the DLR, at least.