Suppose I have the following class definition:
class foo
{
#if bar
private bool bar;
#endif
public void Do()
{
bar = false;
}
}
Is there a way to propagate the preprocessor directive wrapping bar to every place where bar is used. The output should be something like this:
class foo
{
#if bar
private bool bar;
#endif
public void Do()
{
#if bar
bar = false;
#endif
}
}
No, basically. However, what you can do is split your code into two files and make use of partial class
such that all your bar
code is in one isolated file:
partial class foo
{
partial void OnBar(bool value);
public void Do()
{
OnBar(false);
}
}
and
#if bar
partial class foo
{
private bool bar;
partial void OnBar(bool value)
{
bar = value;
}
}
#endif
Now the main file knows nothing about bar
. If the bar
compilation symbol isn't defined, the bar
field doesn't exist, and nor does the OnBar
method - the method and it's invocations simply evaporate.
This can be useful in many scenarios, including additional levels of debugging code, or targeting multiple platforms / frameworks / operating systems (with specific files for different targets) - without your code being filled with #if
.