Early determination

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?
 
J

Jon Skeet [C# MVP]

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
 
K

kodehoved

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
 
S

Sin Jeong-hun

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top