473,761 Members | 5,758 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 4151
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:O5******** ******@TK2MSFTN GP12.phx.gbl...
I think that for features like this the best way to explore the usage is to actually use them. Have you considered modifying mono or rotor and adding
the feature(or permutations of it)? It will give you, and others if you
release it, a chance to see how it would really work in real code.


Actually, it had never occured to my the source to a C# compiler would
be available. Though I'm not sure if I want to attempt adding features to
one. (But I have now downloaded the mono source, and will be looking into
it)
Nov 16 '05 #21

"James Curran" <Ja*********@mv ps.org> wrote in message
news:uq******** ******@TK2MSFTN GP10.phx.gbl...
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:O5******** ******@TK2MSFTN GP12.phx.gbl...
I think that for features like this the best way to explore the usage is to
actually use them. Have you considered modifying mono or rotor and adding
the feature(or permutations of it)? It will give you, and others if you
release it, a chance to see how it would really work in real code.


Actually, it had never occured to my the source to a C# compiler would
be available. Though I'm not sure if I want to attempt adding features to
one. (But I have now downloaded the mono source, and will be looking into
it)

LOL, ya, there is atleast mono's compiler(there is a compiler in rotor as
well, but its in C++(although you're probably better equiped to deal with it
than I) written in C#. I have done some fair amount of modification to the
mcs compiler(bout a half dozen experimental features), so I might be able to
help if you have any problems.

Nov 16 '05 #22
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:O5******** ******@TK2MSFTN GP12.phx.gbl...
I think that for features like this the best way to explore the usage is to actually use them. Have you considered modifying mono or rotor and adding
the feature(or permutations of it)? It will give you, and others if you
release it, a chance to see how it would really work in real code.


Actually, it had never occured to my the source to a C# compiler would
be available. Though I'm not sure if I want to attempt adding features to
one. (But I have now downloaded the mono source, and will be looking into
it)
Nov 16 '05 #23

"James Curran" <Ja*********@mv ps.org> wrote in message
news:uq******** ******@TK2MSFTN GP10.phx.gbl...
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:O5******** ******@TK2MSFTN GP12.phx.gbl...
I think that for features like this the best way to explore the usage is to
actually use them. Have you considered modifying mono or rotor and adding
the feature(or permutations of it)? It will give you, and others if you
release it, a chance to see how it would really work in real code.


Actually, it had never occured to my the source to a C# compiler would
be available. Though I'm not sure if I want to attempt adding features to
one. (But I have now downloaded the mono source, and will be looking into
it)

LOL, ya, there is atleast mono's compiler(there is a compiler in rotor as
well, but its in C++(although you're probably better equiped to deal with it
than I) written in C#. I have done some fair amount of modification to the
mcs compiler(bout a half dozen experimental features), so I might be able to
help if you have any problems.

Nov 16 '05 #24
This makes no sense, if you want access to the indexer, use a for loop.
foreach loops are 50% slower than for loops anyway, which means that you
should use them in very few cases.
Nov 16 '05 #25
SpookyET wrote:
This makes no sense, if you want access to the indexer, use a for
loop. foreach loops are 50% slower than for loops anyway, which
means that you should use them in very few cases.


50%

That's a very specific number...where did you get that info from ?

Rgds Tim.
Nov 16 '05 #26
Tim Jarvis <tj*****@NoSpam ForMe.com> wrote:
SpookyET wrote:
This makes no sense, if you want access to the indexer, use a for
loop. foreach loops are 50% slower than for loops anyway, which
means that you should use them in very few cases.


50%

That's a very specific number...where did you get that info from ?


And in what context? Depending on the type you're indexing, foreach can
be faster than using an indexer.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #27
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, forceach 1.5
secs, 2 secs. You can test it yourself by downloading the code and
playing with it. The fact is that foreach is way slower and it makes
sense to be slower. Take a look at the code behind forceach at
http://www.jaggersoft.com/csharp_standard/15.8.4.htm and see for yourself!

On Sat, 10 Apr 2004 10:17:17 -0700, Tim Jarvis <tj*****@NoSpam ForMe.com>
wrote:
SpookyET wrote:
This makes no sense, if you want access to the indexer, use a for
loop. foreach loops are 50% slower than for loops anyway, which
means that you should use them in very few cases.


50%

That's a very specific number...where did you get that info from ?

Rgds Tim.


Nov 16 '05 #28
> 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, forceach 1.5
secs, 2 secs. You can test it yourself by downloading the code and
playing with it. The fact is that foreach is way slower and it makes
sense to be slower. Take a look at the code behind forceach at
http://www.jaggersoft.com/csharp_standard/15.8.4.htm and see for yourself!

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.

--
cody

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

"cody" <pl************ *************@g mx.de> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
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, forceach 1.5
secs, 2 secs. You can test it yourself by downloading the code and
playing with it. The fact is that foreach is way slower and it makes
sense to be slower. Take a look at the code behind forceach at
http://www.jaggersoft.com/csharp_standard/15.8.4.htm and see for
yourself!

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.
--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk

Nov 16 '05 #30

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
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8814
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...
0
5266
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.