views:

259

answers:

5
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 the emoticon for embarassment?

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

+17  A: 

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.

Brian
This used to be called **full boolean evolution** back in the days of Turbo Pascal and it was configurable whether you still want to evaluate all conditions or not.
Robert Koritnik
oɔɯǝɹ
+2  A: 

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.

Secret Agent Man
+2  A: 

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.

Zeus
+2  A: 

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.

Ikke
A: 

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.

Shiraz Bhaiji