views:

200

answers:

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
+8  A: 

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.

Paul Betts
+2  A: 

#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
A: 

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
A: 

Your design is wrong. Absolutely wrong. This may have been acceptable 20 years ago, but there are much MUCH better techniques for doing what you need here.

You need to break out all your data access logic into interfaces that bear no dependencies on the actual implementation (sql based or oracle based), then use DI/IoC to inject the desired implementation at runtime. Its much simpler than it sounds, works exceedingly great, makes your code easy to test, and allows you to customize and update your application without having to do an entire reinstall.

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

Will
Sure, there exists much better solutions. Maybe that's why I'm asking that. And also I indicated that this is an "assumption". I won't use the solution in that way even there exists. The example is just an example to learn if there exists a way!
yapiskan
Offensive? Sheesh.
Will