I've recently started to learn C# with a good book and now read about the Conditional
attribute and the #if
compiler directive.
I know the usage of the #if
compiler directive:
#if DEBUG
public void foo(int value)
{ ... }
#endif
and of the Conditional
attribute:
[System.Diagnostics.Conditional("DEBUG")]
public void foo(int value)
{ ... }
I also know that the code that is encased by the #if
... #endif
statements doesn't reach the IL but the Conditional
attribute code does and the calls to that function will be ommited.
My question:
Why there is the restriction about the Conditional
attribute usage that functions marked with that attribute have to return void
as written here in the documentation?
You will get a compilation error in Visual Studio if you apply this attribute to a method that does not return void.
I already searched for information but found no explanation.
The compiler does not allow it, because if it were allowed, then the semantics of code like below would be undefined, or at best rather hard to understand:
var x = someMethod(foo());
[System.Diagnostics.Conditional("DEBUG")]
public int foo()
{
return 42;
}
The [Conditional("DEBUG")]
attribute on a method means that both the method and any calls to the method are omitted from the compiled code if the DEBUG
symbol is present.
But if the call to foo()
- which returns a result - disappears from the compiled code, what to pass into someMethod()
? Or if that call is then also removed, what to assign to x
? How to guarantee that the local x
even has a value, which would normally cause a compile error?
The .NET team decided not to go that way, instead they added a compile-time constraint that [Conditional()]
methods must be void
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With