SYSK 157: Conditional Methods
One of the less known features in .NET is conditional methods, which allow developers to create methods whose calls are included or excluded during compilations based on a preprocessing symbol.
Say, you want to execute a certain method only under certain conditions known at compilation time. In the “old days”, you’d use #if…#endif pre-processor definitions. In .NET, you can use the System.Diagnostic.ConditionalAttribute class to do the same:
private void Method1()
{
. . .
Method2();
. . .
}
// NOTE: Make sure to define MYCONDITION conditional compilation symbol in
// project properties -> build tab
[System.Diagnostics.Conditional(“MYCONDITION”)]
private void Method2()
{
. . .
}
In effect, of MYCONDITION is not defined, Method2 call is a no-op. Most commonly used condition is DEBUG…
BEWARE: One would wish that the following would be allowed:
[System.Diagnostics.Conditional(“DEBUG”)]
private void Method2()
{
// TODO: add debug version specific code
}
[System.Diagnostics.Conditional(“RELEASE”)]
private void Method2()
{
// TODO: add release version code
}
But, it will not compile. It’s unfortunate, especially since the following compiles without any problems:
#if DEBUG
private void Method2()
{
// TODO: add debug version code
}
#else
private void Method2()
{
// TODO: add release version code
}
#endif
Well, may be in .NET 3.0?
Comments
- Anonymous
July 17, 2006
PingBack from http://microsoft.wagalulu.com/2006/07/17/sysk-157-conditional-methods/ - Anonymous
July 17, 2006
It's notable that this is done by the compiler not by the framework itself, therefore it is only supported in languages for which the compiler supports it.
-josh - Anonymous
July 17, 2006
.NET 4.0 maybe? as .NET 3.0 is Framework 2.0 + a bunch of frameworks