5

Well, my titling is a bit weird I guess. But let me explain my question.

I have a while loop

while( GetObj() == null || !GetObj().Initialized ){
    doStuff();
}

It would be neat when GetObj() isn't called twice per loop.

I've debugged it in another project to be sure that .NET do not avoid calling the method twice. But that isn't the case.

My actual question now is
Is there a simple way, to avoid calling GetObj() twice in my loop condition?

1
  • Why can't you just put it outside the loop and save it in a variable or something? Commented Aug 8, 2014 at 21:29

3 Answers 3

6

This form is less concise, but possibly more readable.

var obj = GetObj();
while(obj  == null || !obj.Initialized ){
    doStuff();
    obj = GetObj();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any (unless the syntax of course) difference to @marcel-n 's answer? I'm wondering since this one gets upvotes and the other one not a single one?
@Brettetete, One difference is that I answered several minutes earlier, so his answer looks like a duplicate. Normally duplicate answers do not get upvoted. This happens less if the answers are within seconds of each other.
@Brettetete Also his answer doesn't have the same logic as is in your question.
2

I believe this will help:

YourObject obj ;
while((obj = GetObj()) == null || !obj.Initialized) {
    doStuff();
}

Comments

1

Maybe

var obj = GetObj();

while( obj == null || !obj.Initialized ){
    doStuff();
}

1 Comment

Needs to be inside the while loop, as GetObj might change (most likely does).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.