short circuit boolean logic??

  • Thread starter Thread starter John Sparrow
  • Start date Start date
J

John Sparrow

if I say something like:

if (a != null && a.ToString() == "hello") { whatever }

is there any chance the CLR would optimize the code to evaluate the
second operand first, and hence potentially cause an access
violation??

I know many non-.NET languages will do this, the only way to guarantee
operand evaluation order is to say something like:

if (a != null) { if (a.ToString()) == "hello" { whatever } }

Thanks,

John
 
[Removed microsoft.public.dotnet.csharp.general which is not a valid
group.]

John Sparrow said:
if I say something like:

if (a != null && a.ToString() == "hello") { whatever }

is there any chance the CLR would optimize the code to evaluate the
second operand first, and hence potentially cause an access
violation??

Assuming you're talking about C#, no. The C# specification states:

<quote>
The && and || operators are conditional versions of the & and |
operators:

* The operation x && y corresponds to the operation x & y, except that
y is evaluated only if x is true.

* The operation x || y corresponds to the operation x | y, except that
y is evaluated only if x is false.
</quote>
 
No, it won't reverse the order in which boolean statements are
executed/evaluated.

BTW, if you use & instead of &&, then it will execute both of them first,
and then evaluate for true/false.
 
Back
Top