Why conditional attribute methods are not allowed to return other than void

I recently started learning C # with a good book and now read about the Conditional attribute and the #if compiler #if .

I know the use of the #if compiler #if :

 #if DEBUG public void foo(int value) { ... } #endif 

and the Conditional attribute:

 [System.Diagnostics.Conditional("DEBUG")] public void foo(int value) { ... } 

I also know that the code enclosed in the #if ... #endif statements does not reach IL, but the code of the Conditional attribute is executed, and calls to this function will be skipped.

My question is:
Why is there a restriction on the use of the Conditional attribute, functions marked with this attribute should return void as written here in the documentation ?

In Visual Studio, you get a compilation error if you apply this attribute to a method that void does not return.

I was already looking for information, but could not find any explanation.

+5
source share
1 answer

The compiler does not allow this, because the semantics of code like this will be undefined or, at best, quite difficult to understand:

 [System.Diagnostics.Conditional("DEBUG")] public int foo() { ... } var x = someOtherMethod(foo()); 

The [Conditional("DEBUG")] attribute for a method means that method calls are excluded from compiled code if the "DEBUG" character is present.

But if the call to foo() disappears from the compiled code, what is passed to someOtherMethod() ? Or, if this call is also deleted, what to assign x ? How to guarantee that local x even has a value that usually causes a compilation error?

The .NET team decided not to go this way, instead they added a compilation time limit, which the [Conditional()] methods should be invalid.

+3
source

Source: https://habr.com/ru/post/1270309/


All Articles