문제

I have C/C++ background. I usually put heavy assertions on my code, and in C or C++ there's no guaranteed way to eliminate evaluation of subexpressions which is assertion parameter. So I had to use macro.

In C#, I don't have that level of macro support. But I have Conditional attribute. In my experience with C and C++, subexpressions cannot be eliminated due to side-effects.

For example,

[Conditional(DEBUG)]
void func1(int a)
{
    //  Do something.
}
int func2()
{
    //  Will this be called?
}

func1(func2());

If func2 is still being called, I should code like isDebugMode() && func1(func2()). But this is what I really want to avoid. So I want to know the Conditional attribute guarantees elimination of subexpressions or not.

If it doesn't, what's the best practice to write debug build assertion which will be completely stripped at release build?

AFAIK, this is compiler specific support. I want to know the case of Mono compiler.

도움이 되었습니까?

해결책

func2 won't be called. It is stated in C# Language Specification so Mono compiler must act according to these rules.

MSDN http://msdn.microsoft.com/en-us/library/aa664622(v=vs.71).aspx:

The attribute Conditional enables the definition of conditional methods. The Conditional attribute indicates a condition by testing a conditional compilation symbol. Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. If the symbol is defined, the call is included; otherwise, the call (including evaluation of the parameters of the call) is omitted.

다른 팁

func2() won't be called, because the call the func1() will be completely removed.

If you are intending to use this feature for assertions, you might want to consider using Code Contracts.

You will be able to add parameter validation and other assertions which can optionally be completely stripped from release builds (there is a post-processor which does the stripping).

To validate an argument you can do something like this:

public void Test(int value)
{
    Contract.Requires((0 < value) && (value < 10));
    // ...
}

And you can assert conditions like this:

Contract.Assume(something != 0);

The Line

func1(func2());

will be deleted if DEBUG == false

In c# there are macros too, but they are different than c++.

You can declare a macro in the Conditional Compilation Symbols and check them like that

#if MACRO
#endif

Here you can read the documentation about them.

Hope it helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top