4

I wonder if there is a way to set the value of #define in run time.

I assume that there is a query for Oracle specific and Sql Server specific at the code below.

#define oracle

// ...    

#if oracle
// some code
#else
// some different code.
#endif
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Ali Ersöz
  • 15,422
  • 11
  • 48
  • 63

3 Answers3

15

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

Ana Betts
  • 72,589
  • 16
  • 137
  • 204
2

#if is compile-time. You could specify this in your build process (via switches to msbuild/csc), but not really at runtime. The excluded code doesn't exist. You might be better advised to (1 of):

  • Have separate DAL stacks for each back-end, using Dependency Injection / IoC
  • Use an ORM tool that supports either
  • Branch the code based n the provider (in a single DAL)
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
0

No, the preprocessor runs before compile and can alter code at that time, that is its purpose, if you want to switch behavior based on something at runtime use a variable and normal conditional logic.

Louis Gerbarg
  • 43,216
  • 8
  • 78
  • 88