Is this valid?
byte ptr[];
...
if (null != ptr && ptr.Length > 0) {
...
}
(It would be in C)
Or should I break it apart:
if (null != ptr) {
if (ptr.Length > 0) {
...
}
}
Tom Porterfield - 17 Nov 2006 16:04 GMT
> Is this valid?
>
[quoted text clipped - 3 lines]
> ...
> }
This is fine as the expression is evaluated left to right in C# and the if
will be exited when the first condition is found that evaluates to false.
So if your ptr is null, the ptr.Length code will never execute.
> (It would be in C)
> Or should I break it apart:
[quoted text clipped - 4 lines]
> }
> }
You can do it this way if you like, but it isn't necessary.

Signature
Tom Porterfield
Dave Sexton - 17 Nov 2006 16:07 GMT
Hi Jamie,
They do the same thing, but I prefer the first one because it fits nicely on
one line. BTW, it's more common in C# to write it as follows:
if (ptr != null && ptr.Length > 0)
{
...
}
The compiler prevents accidental assignment to ptr because it requires the
expression to evaluate to a boolean, not byte[].

Signature
Dave Sexton
> Is this valid?
>
[quoted text clipped - 12 lines]
> }
> }
Bryan - 17 Nov 2006 16:07 GMT
Yes, C# will short-circuit that if the first condition is false. That is
part of the C# spec and every compiler should honor that. I believe in the
C/C++ world, that sort of thing is up to the compiler vendor. In C# you can
count on it being there (unless you have a nonstandard compiler vendor).
A side note: you should write ptr != null instead of the other way around.
It reads better to someone looking at your code. All the reasons you did it
the other way around in C are no longer valid in C#.
> Is this valid?
>
[quoted text clipped - 12 lines]
> }
> }
Mark Wilden - 17 Nov 2006 18:03 GMT
> Yes, C# will short-circuit that if the first condition is false. That is
> part of the C# spec and every compiler should honor that. I believe in
> the
> C/C++ world, that sort of thing is up to the compiler vendor.
Short-circuit evaluation is also required by the language definition in C
and C++ and always has been. It was just another delight for me when moving
from BASIC and Pascal.
///ark