473,703 Members | 3,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[Feature Request] "first:" "last:" sections in a "foreach" block

I'd like to make the following proposal for a new feature for the C#
language. I have no connection with the C# team at Microsoft. I'm posting
it here to gather input to refine it, in an "open Source" manner, and in an
attempt to build a ground-swell of support to convince the folks at
Microsoft to add it.
Proposal: "first:" "last:" sections in a "foreach" block

The problem:
The foreach statement allows iterating over all the elements of a
collection. However, often the first or last element of the collection must
be handled differently than the others in the collection. For example, if
we were generating a list of items for display, we'd want a comma after
every item except the last. In these cases, foreach cannot be used, and the
alternates which can be used are generally ugly and often less efficient
than foreach. An elegant solution keeping with the concept of C# is needed.

The proposal:
I suggest adding four new keywords (only available inside foreach block) to
direct the compiler to our exact intentions. "first:" "last:" "other:"
"all:"

Example:
foreach (Person p in personCollectio n)
{
first:
Console.WriteLi ne("Names: {0},", p.Name");
other:
Console.WriteLi ne(" {0},", p.Name");
last:
Console.WriteLi ne(" {0}", p.Name");
}
A block not preceeded by one of those keywords would be assumed to be an
"all:" block, exact as is the case now.

Analysis:
The advantages of the feature:
It solves a problem in an elegant way, keeping with the design concepts of
C#.
It is handled entirely by the compiler, so that it has ZERO effect on code
that does not use it, and it requires no changes to the class framework or
the CLR. (These were problems with other suggested solutions for this)

The disadvantages:
It requires four keywords, although this could be reduced to three
(eliminating "all:") and, they would each be very context sensitive, so the
conflicts with user-defined identifiers is unlikely.

Implementation:
Presently, a foreach construct is largely "syntactic sugar" around a while
loop using an IEnumerator, such that code written as
foreach (int i in arry)
{
Console.WriteLi ne(i);
}

Would be compiled much as if it were written:
IEnumerator n = arry.GetEnumera tor();
while(n.MoveNex t())
{
int i = (int) n.Current;
Console.WriteLi ne(i);
}

Similarly, code using these blocks would also have a direct translation:
foreach (int i in arry)
{
First:
Console.WriteLi ne("{0} - first", i);
Others:
Console.WriteLi ne(i);
}

Would be compiled as:
IEnumerator n = arry.GetEnumera tor();
if (n.MoveNext())
{
int i = (int) n.Current;
Console.WriteLi ne("{0}-- first ", i);
while(n.MoveNex t())
{
i = (int) n.Current;
Console.WriteLi ne(i);
}
}
(The internal representation of a "last:" block is a bit more involved, but
still basically straightforward )

Any comments are suggestion would be appreciated.

Truth,
James Curran
MVP (for .um. VC++)

Nov 16 '05
32 4140
SpookyET wrote:
It isn't a real number. There is this episode of the .NET Show
called Code Optimizations at
http://msdn.microsoft.com/theshow/Ep...27/default.asp where it
shows you on how to optimize your code. A for loop took 1sec,


The problem with this type of benchmark in a demo is this, the point
that they are trying to make is that you need to look at specific areas
to tune your code, and they are giving a for instance...

Our product managers and technical sales guys do the same kind of thing
when they are demo'ing Optimise it (I work for Borland) and they will
show some code that needs to be optimised, the biggest impact is when
they show reasonable looking code that performs poorly. It is usually a
pretty bogus piece of code to be honest, but that is not the point of
the demo, the demo is to show how the poorly performing code can be
found.

I would not dispute that a foreach performs worse in some situations
than other loop types, and I would agree that if you are code tuning
that this is an area to look at, perhaps using a monitoring tool would
be another course of action ;-) But I would not be so bold as to quote
percentage figures, especially from a demo, that is specifically
designed around tuning code, that's just asking for dispute.

IMO when tuning code, sometimes a piece of code that performs
adequately, but is very clear in it's intent is better to have in your
source than highly performing, but slightly less obvious code, I think
that too many people leave the time taken in trying to understand old
code out of the equation when code tuning.

Please don't take this to mean that I don't advocate tuning code
(including foreach's) because that is *not* the case, but I think that
some sense needs to be applied and not based upon a MS demo in a code
tuning tutorial, the critera needs to be based upon the requirements of
the application balanced against the requirements of maintenance.

Rgds Tim.
Nov 16 '05 #31
Daniel O'Connell [C# MVP] wrote:
treating a foreach like a switch would allow you to modify the syntax
without disrupting existing code. Two word keywords are syntactically


For me this would be the key thing, I would hope the obvious thing as
well ;-)

Rgds Tim.
Nov 16 '05 #32
> > This is not always true. for example with arrays a for loop should
perform
with
the same speed as foreach since here are no Enumerators involved. Also, though I can't remember which structures specifically, there are

cases where foreach will result in better performance than for. Things like linked lists, trees, etc may be faster via a foreach since its possible for the
foreach to be written so that it doesn't have to iterate the collection
every time. An indexer would.

Additionally, the jitter removes the range-check when enumerating over an
array or a string or a StringBuffer.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #33

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

32
578
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
0
8662
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7853
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6585
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4420
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2434
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2057
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.