Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Pre-processor directive scope

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?

like image 231
TK. Avatar asked Nov 17 '08 08:11

TK.


3 Answers

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.

like image 152
Jon Skeet Avatar answered Oct 05 '22 03:10

Jon Skeet


Although could you not go down the route of Mock objects, ala Mock.Rhinos ?

like image 32
Chris Kimpton Avatar answered Oct 05 '22 03:10

Chris Kimpton


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
like image 35
Ali Ersöz Avatar answered Oct 05 '22 04:10

Ali Ersöz