Search code examples
c#reflectioncompatibilitypreprocessor-directive

C# precompiler directive to avoid reflection


In my scenario i have some version of the same library.

For example suppose that my library name is lib.dll and there are two version of that library.

In this example each library contain only one class ( called Dummy ) with only one method, but the method's signature change in each library depending on the version.

Now i need to develop a new library that use the previous lib.dll but need to be compatible with each version.

Suppose that lib.dll with versione 1.0.0.0 support that method :

Dummy.Method ( int )

lib.dll with version 2.0.0.0 instead suppot that method :

Dummy.Method ( string , int )

In the library that i am developing using lib.dll i would be able to be retrocompatible with both lib.dll versions but without use reflection to call the method with different signature. Is there any support to precompiler syntax like that :

 #IF lib.dll VERSION IS 1.0.0.0 
      Dummy.Method ( 1 ) ;
 #ENDIF

 #IF lib.dll VERSION IS 2.0.0.0 
      Dummy.Method ( "test" , 1 ) ;
 #ENDIF

so that according to the referenced version of the library; one branch of code, or the other is used.


Solution

  • C# under Visual Studio 2019 does have a facility to achieve this.

    They are called generators.

    (see https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/).

    The idea is to create your method during compile time. The generator would thus check the version of the lib.dll version and generate adequate code for calling the actual method - Dummy.method() above.