www.digitalmars.com         C & C++   DMDScript  

D - using and foreach statements

reply anonymous <anonymous_member pathlink.com> writes:
Two features that I like and may not be difficult to put in a compiler are
1) using statement
2) foreach statement

The using statement is a block that calls dispose() at the end to cleanup
resourses.  For example:
using(DatabaseConnection db = new DatabaseConnection()) {
db.open();
// various statements
}

is converted to the following code:

DatabaseConnection db = new DatabaseConnection();
try {
db.open();
// various statements
}
finally {
db.dispose();  
}

The using statement encourages connections, files, etc to get closed at the end
of the block with a syntax that is easy to read.  The converted code uses a try
block, but you learn at the end that the block is only used for managing
resources, not error handling.  The using statement is clearer, b/c it declares
up front that the block is for managing resources.

The other statement I like is foreach.  You guys probably know it well.  Quickly
it is:
foreach(string str in myArray) {
//stuff
}

is the same as:
IEnumerator enum = myArray.GetEnumerator();
while(enum.moveNext()) {
string str = (string)enum.current();  //is there a type-safe way of doing this?
//stuff
}

The myArray object implements IEnumerable (not IEnumerator).
Jan 12 2003
parent "Walter" <walter digitalmars.com> writes:
Some sort of foreach is going to get added. It's just the particular
syntax/semantics that needs to be worked out. for the "using statement", I
think that the auto attribute should fit the bill. -Walter

"anonymous" <anonymous_member pathlink.com> wrote in message
news:avsl07$egn$1 digitaldaemon.com...
 Two features that I like and may not be difficult to put in a compiler are
 1) using statement
 2) foreach statement

 The using statement is a block that calls dispose() at the end to cleanup
 resourses.  For example:
 using(DatabaseConnection db = new DatabaseConnection()) {
 db.open();
 // various statements
 }

 is converted to the following code:

 DatabaseConnection db = new DatabaseConnection();
 try {
 db.open();
 // various statements
 }
 finally {
 db.dispose();
 }

 The using statement encourages connections, files, etc to get closed at

 of the block with a syntax that is easy to read.  The converted code uses

 block, but you learn at the end that the block is only used for managing
 resources, not error handling.  The using statement is clearer, b/c it

 up front that the block is for managing resources.

 The other statement I like is foreach.  You guys probably know it well.

 it is:
 foreach(string str in myArray) {
 //stuff
 }

 is the same as:
 IEnumerator enum = myArray.GetEnumerator();
 while(enum.moveNext()) {
 string str = (string)enum.current();  //is there a type-safe way of doing

 //stuff
 }

 The myArray object implements IEnumerable (not IEnumerator).

Jan 12 2003