开发者

This is useful but I'm not sure why it works

开发者 https://www.devze.com 2022-12-11 00:20 出处:网络
protected override Boolean IsValid(String propertyValue) { return !String.IsNullOrEmpty(propertyValue) && propertyValue.Trim().Length > 0;
protected override Boolean IsValid(String propertyValue)
{
    return !String.IsNullOrEmpty(propertyValue) && propertyValue.Trim().Length > 0;
}

This C# validation method does exactly what I want, but I wasn't aware that you could use expression short-circuiting like this.

When propertyValue is null, doesn't execution still need to evaluate the second part of the expression to yield a boolean result, and if so why doesn't the second part then throw a null ref exception for the Trim().Length > 0 call?

I assume that the second part is evaluating to false or to null, but I am curious to know what is going on here.

Apologies if I'm missing something really obvious, please enlighten me.

God - I was missing something obvious what an idiot! - total blank on the fact that when the first part is false the second part is irrelevant and I even KNEW it was short-ciruciting - sorry for wasting people's time, what's th开发者_开发知识库e emoticon for embarassment?

Added another tag to reflect my embarrassment at typing before thinking.


This is what short-circuiting does. When you have

e1 && e2

and e1 evaluates to false, e2 is not evaluated at all.

(And for

e1 || e2

if e1 is true, e2 is not evaluated at all.)

This is important to understand in the case where e2 has "effects" (does I/O, throws an exception, ...) as short-circuiting yields different program semantics than full evaluation would.


In order for a conjunction to be true, both of its components need to be true. Due to this definition, and because C# evaluates the left conjunct first, if the left conjunct evaluates to false, then the answer is already false, and C# does not need to evaluate the right conjunct.


This is because of the && operator

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

from MSDN

Is a nice feature to know about :)

If you have

A AND B

if A is false, A and B will always evaluate to false, so it doesnt really matter what B is.


This is what short-circuit means. When the first operand yields false, the second part does not need to be evaluated, because the result will be false anyways.


There is an add (&&). So when the first part is false it does not need to evaluate the second part.

This is much better than the old VB 6 days, when that statement would have resulted in a null reference exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号