Early determination

  • Thread starter Thread starter Sin Jeong-hun
  • Start date Start date
S

Sin Jeong-hun

if( (myList!=null) && (myList.Count>10) )
{
Do something....
}

The code above throws an exception if "myList" is null. Even though
the left condition is false so that the whole condition must be false,
it looks like C# also tries to evaluate the right condition. To avoid
the exception I have to code as

if( myList!=null )
{
if( myList.Count>10 )
{
Do something....
}
}

This can be trivial but,it requires a little more typing and rows in
the source code. I think C# doesn't need to check the right condition
in this situation, What do you think?
 
if( (myList!=null) && (myList.Count>10) )
{
Do something....

}

The code above throws an exception if "myList" is null.

No, it doesn't. Are you sure you haven't got a single & instead of a
double one? C# is definitely designed to handle this situation.

Could you post a short but complete program demonstrating the problem?
See http://pobox.com/~skeet/csharp/complete.html for what I mean by
that.

Jon
 
No, it doesn't. Are you sure you haven't got a single & instead of a
double one? C# is definitely designed to handle this situation.

Could you post a short but complete program demonstrating the problem?
Seehttp://pobox.com/~skeet/csharp/complete.htmlfor what I mean by
that.

Jon

I agree with Jon. Unless you have multiple threads modifying myList at
the same time C# will do as you expect, i.e. evaluate only as much of
the expression as necessary. Actually, in a release build the two
pieces of code compile to the exact same IL.

If you do in fact have multiple threads here, both solutions are
equally flawed as checking and accessing myList is not a single
operation in either of the cases. In that case, you need
synchronization.

Brian
 
I agree with Jon. Unless you have multiple threads modifying myList at
the same time C# will do as you expect, i.e. evaluate only as much of
the expression as necessary. Actually, in a release build the two
pieces of code compile to the exact same IL.

If you do in fact have multiple threads here, both solutions are
equally flawed as checking and accessing myList is not a single
operation in either of the cases. In that case, you need
synchronization.

Brian

That was weird. I tested it but it caused no exception. Actually, that
was not exactly the same situation which I usually encounter while I'm
programming. I can't recreate the code that caused an exception right
now. When I it comes to me, I will post it again.

I'm sorry for having caused troubles by asking you a wrong question.
Thank you.
 
Back
Top