c# Pre-processor directive scope
-
08-07-2019 - |
Question
I'm looking to use:
#define
and
#if
to allow me to simulate potentially absent hardware during unit tests. What are the rules for using the #define
statements?
i.e. what is its default scope? can I change the scope of the directive?
Solution
As Chris said, the scope of #define is just the file. (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't!
You can also define a symbol project-wide, but that's done with project properties or a compiler switch rather than being specified in source code.
OTHER TIPS
From MSDN, its scope is the file
Although could you not go down the route of Mock objects, ala Mock.Rhinos ?
Yes as Chris mentioned, its scope is the whole file. You can use the defined keyword anywhere in the file.
i.e;
#define something
... some code ...
and in any method, class body or namespace, you could use it like;
#if something
... some conditional code ...
#else
... otherwise ...
#endif
The scope of a preprocessor directive starts when it's parsed from the source and persists until directed otherwise. If you do want to limit the scope of a preprocessor directive, use the "undef" declaration it switch off when your done with it.
#include <iostream>
using namespace std ;
int main()
{
#define someString "this is a string"
cout<<someString<<endl;
#undef someString // scope of someString ends here
cout<<someString<<endl; //this causes a compile error
return 0 ;
}