CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Peter's Gekko

public Blog MyNotepad : Imho { }

do while, do not repeat

In C# you can express a lot using with a minimal set of statements. One of the active goals of the C# team is to keep the language as simple and small as possible. Another (small) example of this is the flexbility of the while statement. Take this snippet of code

string dirName = @"C:\USR";
string fileName = "*.cs"
;
bool fileMissing = true;

while(fileMissing)
{
   fileName = myFiddleFuction(fileName);
   fileMissing = Directory.GetFiles(dirName, fileName).Length == 0;
}

This can also be expressed as :

string dirName = @"C:\USR";
string fileName = "*.cs";

do
{  
   fileName = myFiddleFuction(fileName);
}
while(Directory.GetFiles(dirName, fileName).Length == 0);

The control variable fileMissing, which had to make sure the loop was executed at least once, is gone. If you ever worked with a language like Pascal (Delphi) you'll propably recognize the repeat statement.

Peter



Comments

Peter van Ooijen said:

Wirth it is !

It's hard to compare for in a language like pascal with for in C#. In Pascal the number of iterations is determined at the start of the loop. To break out of the loop you need something like a break;
In C# an expression is evaluated on every iteration, you can even code something like
for (;Directory.GetFiles(dirName, fileName).Length == 0;)
{
fileName = myFiddleFuction(fileName);
}
Which is impossible in Pascal.
# February 19, 2004 6:21 AM

Peter's Gekko said:

FORe a WHILE
# February 19, 2004 7:55 AM

Kirk Graves said:

Nice compact code sample, but it is also much less readable then the first sample, and there would be no appreciable performance advantage.

Having worked on projects with multiple developers on many occasions, and where each of those developers was at a different level of expertise, I find readable code to be the second most important issue when deciding how to implement a particular algorythm. (The first is of course performance).
# February 19, 2004 9:28 AM

Peter van Ooijen said:

Isn't that excactly what Frans is pointing at ? Using do while makes it explicit that the code loop in the loop always has to run. Which could be crucial. Maybe a login would have made a better example.
# February 19, 2004 1:48 PM

James Curran said:

The second could be written as:

do
{
fileName = myFiddleFuction(fileName);
} while(Directory.GetFiles(dirName, fileName).Length == 0);


while more readable, this version also more clearly shows what's different between the "while" and "do..while" versions
# February 19, 2004 2:48 PM

Peter van Ooijen said:

Thanks James, post is updated.
# February 20, 2004 12:40 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!