views:

60

answers:

4

I discovered a very puzzling behavior for the following code:

public double ReturnBehavior(List<double> ptList)
{
    return ptList.Count==0? 0:ptList[0];
}

I thought it should be equivalent to

public double ReturnBehavior(List<double> ptList)
{
    if(ptList.Count==0)
       return 0;
    return ptList[0];
}

But it is not, because the first method will evaluate both true and false condition together. So this means that first method will try an IndexOutOfRange exception if ptList.Count==0.

Am I missing something here? Or is it a bug in vs 2008?

A: 

They ought to behave the same. The ternary operator uses short-circuit semantics. If the test passes, only the first expression is evaluated, otherwise, only the second expression is evaluated. Are you actually seeing an exception?

Marcelo Cantos
A: 

No IndexOutOfRange exception in VS2010.

sfjedi
+1  A: 

I've checked both in VS2010 and VS2008, behavior is expected - no exceptions. If you have errors - they are not in the given code fragment

desco
Yes, I also tried it and there is no error in the given code.Also check http://msdn.microsoft.com/en-us/library/ty67wk28.aspxIt's clearly mentioned "Only one of the two expressions is evaluated"
Vivek Athalye
A: 

I think that in some cases, if you have a multicore processor, the compiler will tell the processor to evaluate ahead if possible. At least i know that's the case when for example i have an if(condition1 && condition2), on some computers it will evaluate both conditions in parallel, and this means it evaluates the second condition even if the first fails.

scripni
Source for this? I find this very hard to believe, as the short circuiting of logical operators is well documented in C#
recursive
I can't believe that. There are often cases where people count on short circuits and if both sides evaluated then exceptions would be thrown. This would be a huge issue.
Mike M.
Maybe list here is shared between different threads? There are no locks here so it is possible to pass check and fail on index access if another thread clears this list between these two operations
desco
my mistake, i think i might have seen this functionality in a c++ compiler, not sure where i read about this... anyway i checked http://msdn.microsoft.com/en-us/library/2a723cdk%28VS.71%29.aspx and it seems that the short-circuit evaluation does work as expected in C#.Again, sorry for the mistake, this is what i get for not getting my facts straight before posting the answer.
scripni