user3129535
user3129535

Reputation: 71

How to avoid while-loop code duplication?

string s = Console.ReadLine();
while(s != null)
{
    // do something 
    //   ....
    s = Console.ReadLine(); 
}

The code above is to get the input, verify it, process it and then input again, but obviously, s = Console.ReadLine(); is code duplication.

What tricks are there to avoid the duplication?

Upvotes: 3

Views: 405

Answers (2)

chepner
chepner

Reputation: 532053

In Python (where there is no do-while loop to guaranteed at least one iteration), the trick is to use an infinite loop with an explicit break.

while( true )  // Or whatever evaluates to true unconditionally
{
    s = Console.ReadLine();
    if (s == null) {
        break;
    }
    // do something
}

Upvotes: 2

acushner
acushner

Reputation: 9946

depending on language, you can often do something like this:

while (s = Console.ReadLine())
{
    ...
}

Upvotes: 2

Related Questions