简体   繁体   中英

Debug Assert condition logic and language peculiarities

I am not native English speaker, so for me is a little strange the Debug.Assert method, that, for me, verifies a condition, in fact, verifies the opposite of this condition.

Assert = advance, affirm, argue, attest, aver, claim, proclaim, profess, pronounce, put forward, say, stress, etc

I expect, that the

Debug.Assert(Me.Member Is Nothing, "Member Is Nothing!")

behave like

Affirm(condition, "Message") ' conditional message

However, in reality I should do

Debug.Assert(Me.Member Is Nothing, "Member Is NOT Nothing!")

Affirm(NOT condition, "Message") ' counter-conditional message

Do I miss something?

Do you see this intuitive or not?

You have the syntax correct, but think of it this way

Debug.Assert(Me.Member Is Nothing, "Member assert.")

This will assert that Me.Member is Nothing , and will only alert you when it's not. Kind of like if you were in an argument and you said "The Earth is 75% water." Not too many people are going to argue with you on that. But if you said "The Earth is mostly made up of chocolate cake." People would argue.

So too with Assert, if the assertion is true, no need for the debugger to speak up. If it's false, it needs to let you know.

By the way, I'm a native English speaker, and the first few times I wrote assert statements, I wrote them backwards :)

The API for Debug.Assert is indeed a bit counter-intuitive. It took me a long time to get used to this. In my head the Assert translated to this:

if (condition)
{
    Fail(message);
}

But in fact, it translated to:

if (condition)
{
    // Success
}
else
{
    Fail(message);
}

or in short:

if (!condition)
{
    Fail(message);
}

The trick is that the boolean expression should be true not to assert. I think however this design was picked, because this API has been available for C++ developers for a long time and swapping it around would dazzle them.

The point is that your assumption of the Assert method is a bit off the mark.

I mean, the function checks if the condition is valid, that is, TRUE. So it ASSERTS that the condition.

IF the condition is not met, that is, FALSE, the message is displayed.

With Assert , you verify the logic in your code. Optionally, you can add a message to help with debugging should an assertion fail.

int i = 3;
i *= 3;
assert(i == 9, "Strange arithmetic failure");

(Sorry for the C++ code.)

You are not missing anything. Perhaps the designers should have called the method "IfNot" instead of "Assert". I suppose they did not mean an Assert call to be read like an "if" statement. "Assert" as a method name for checking values also has a long history in C/C++, so I guess they wanted to use the same name in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM