Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Conditional attribute methods aren't allowed to return other than void

Tags:

c#

.net

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.

like image 350
Andre Kampling Avatar asked Jul 28 '17 07:07

Andre Kampling


1 Answers

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.

like image 155
Peter B Avatar answered Oct 24 '22 05:10

Peter B