Is there a way to set the #define value at runtime?

I wonder if there is a way to set the #define value at runtime.

I am assuming there is a request for the code below for specific Oracle and Sql server.

#define oracle

// ...    

#if oracle
// some code
#else
// some different code.
#endif

      

+1


source to share


4 answers


Absolutely not, #defines are compiled by the preprocessor before the compiler even sees it, so the "oracle" token is not even in your code, just "1" or "0". Change #define to a global variable or (better) a function that returns the correct value.



+12


source


#if

- compilation time. You can specify this in your build process (using switches in msbuild / csc), but not at runtime. The excluded code does not exist. You may be recommended (1 of):



  • Each individual package has separate DAL stacks using Injection Injection / IoC
  • Use an ORM tool that supports
  • Introduce provider based code (in one DAL)
+2


source


No, the preprocessor is run before compilation and can change the code at this time, that is, its purpose, if you want to switch behavior based on something at runtime, use variable and normal conditional logic.

0


source


Your design is wrong. Absolutely wrong. This may have been acceptable 20 years ago, but there are a LOT of better methods for doing what you need to do here.

You need to break all your data access logic into implementation independent interfaces (sql or oracle based) and then use DI / IoC to inject the desired implementation at runtime. It's much easier than it sounds, works tremendously, makes your code testable, and allows you to tweak and update your application without having to reinstall it.

Related questions:
https://stackoverflow.com/questions/45191/ioc-explain-and-more-important-when-to-use-it
Inversion of control from .net
https://stackoverflow.com/questions/71041/which -single-iocdi-container-would-you-recommend-using-and-why

-2


source







All Articles