I was recently going through some code and considering whether I need to be careful with the expressions placed inside Debug.Assert
statements, such as expensive operations or those with side effects. However, it appears the compiler is pretty smart about completely removing the Assert
statement and inner expressions.
For example, the following will only print on debug builds:
static void Main(string[] args)
{
Debug.Assert(SideEffect());
}
private static bool SideEffect()
{
Console.WriteLine("Side effect!");
return true;
}
And this will complain that o
is being used before initialization on release builds:
static void Main(string[] args)
{
object o;
Debug.Assert(Initialize(out o));
o.ToString();
}
private static bool Initialize(out object o)
{
o = new object();
return true;
}
It even seems to stand up to expressions such as this (printing "After" in both cases):
static void Main(string[] args)
{
if (false) Debug.Assert(true);
Console.WriteLine("After");
}
I was a little suprised with how smart the compiler is here and its ability to correctly detect cases when the Debug.Assert
is removed. So, it got me curious..
- How exactly is the statement removed? The expression tree must be built before the statement is removed in order to properly execute the above
if
statement correctly. - Is the
System.Diagnostics.Debug
class special here, or is it possible to build your own methods with similar handling? - Are there any ways to "trick" the preprocessor here? Even better, are there situations that one might encounter in real-world code where this could be problematic?