<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# Help &#187; Looping</title>
	<atom:link href="http://www.csharphelp.com/tag/looping/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.csharphelp.com</link>
	<description>C# Tutorial and Guides</description>
	<lastBuildDate>Tue, 07 Feb 2012 01:03:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The Internals of C# foreach</title>
		<link>http://www.csharphelp.com/2007/09/the-internals-of-c-foreach/</link>
		<comments>http://www.csharphelp.com/2007/09/the-internals-of-c-foreach/#comments</comments>
		<pubDate>Tue, 18 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Looping]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=670</guid>
		<description><![CDATA[Many moons ago I discussed the foreach loop. Iexpand on that post here as I continue my series for the MSDN C#Developer Center. The advantage of a foreach loop over a forloop is the fact that it is unnecessary to know the number of itemswithin the collection when an iteration starts. This avoids iteratingoff the [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">Many moons ago I discussed the foreach loop. Iexpand on that post here as I continue my series for the MSDN C#Developer Center. </span></p>
<p><span class="smallblack">The advantage of a foreach loop over a forloop is the fact that it is unnecessary to know the number of itemswithin the collection when an iteration starts. This avoids iteratingoff the end of the collection using an index that is not available. AsBill Wagner pointed out in his Custom Iterators article last week, aforeach loop also allows code to iterate over a collection withoutfirst loading the collection in entirety into memory. In this article Iam going to explore how the foreach statement works under the covers.This sets the stage for a follow on discussion of how the yieldstatement works. </span></p>
<p><span class="smallblack"><b>foreach with Arrays</b></span></p>
<p><span class="smallblack">Consider the foreach code listing shown in Listing 1: </span></p>
<p><span class="smallblack">Listing 1: foreach with Arrays </span></p>
<p><span class="smallestblack"><span class="smallblack">int[] array = new int[]{1, 2, 3, 4, 5, 6};<br />foreach(int item in array)<br />{<br /> Console.WriteLine(item);<br />}<br /></span>
<p><span class="smallblack">From this code, the C# compiler creates CIL equivalent of a for loop like this (Listing 2): </span></p>
<p><span class="smallblack">Listing 2: Compiled Implementation of foreach with Arrays </span></p>
<p><span class="smallestblack"><span class="smallblack">int[] tempArray;<br />int[] array = new int[]{1, 2, 3, 4, 5, 6};<br />tempArray = array;<br />for (int counter=0; (counter &lt; tempArray.Length); counter++)<br />{<br /> readonly int item = tempArray[counter];<br /> Console.WriteLine(item);<br />}<br /></span>
<p><span class="smallblack">Since the collection is an array and indexingthe array is fast, the foreach loop implementation relies on supportfor the Length property and the index operator ([]). However, these twoarray features are not available on all collections. Many collectionsdo not have a known number of elements and many collection classes donot support retrieving elements by index. </span></p>
<p><span class="smallblack"><b>foreach with IEnumerable&lt;T&gt;</b></span></p>
<p><span class="smallblack">To address this, the foreach loop uses the System.Collections.Generic.IEnumerator&lt;t&gt;.(Given C# 2.0.s generics support, there is very little reason toconsider using the non-generic equivalent collections so I will ignorethem from this discussion except to say their behavior is almostidentical.) IEnumerator&lt;t&gt; is designed to enable the iterator patternfor iterating over collections of elements, rather than thelength-index pattern shown in earlier. IEnumerator&lt;t&gt; includes threemembers. The first is bool MoveNext(). Using this method, we can movefrom one element within the collection to the next while at the sametime detecting when we have enumerated through every item using theBoolean return. The second member, a read-only property called Current,returns the element currently in process. With these two members on thecollection class, it is possible to iterate over the collection simplyusing a while loop as demonstrated in the code listing below (Listing3): &lt;/t&gt;&lt;/t&gt;&lt;/t&gt;</span></p>
<p><span class="smallblack">Listing 3: Iterating over a collection using while </span></p>
<p><span class="smallestblack"><span class="smallblack">System.Collections.Generic.Stack&lt;int&gt; stack =<br /> new System.Collections.Generic.Stack&lt;int&gt;();<br />int number;<br />// &#8230;<br />// This code is conceptual, not that the actual code.<br />while(stack.MoveNext())<br />{<br /> number = stack.Current;<br /> Console.WriteLine(number);<br />}<br />&lt;/int&gt;&lt;/int&gt;</span>
<p><span class="smallblack">The MoveNext() method in this listing returnsfalse when it moves past the end of the collection. This replaces theneed to count elements while looping. (The last member on IEnumerator&lt;t&gt;,Reset(), will reset the enumeration.) This while listing shows the gistof the C# compiler output, but it doesn.t actually work this waybecause it omits two important details about the actual implementation:interleaving and error handling. &lt;/t&gt;</span></p>
<p><span class="smallblack"><b>Interleaving</b></span></p>
<p><span class="smallblack">The problem with is that if there are two (ormore) interleaving loops over the same collection, one foreach insideanother, then the collection must maintain a state indicator of thecurrent element so that when MoveNext() is called, the next element canbe determined. The problem is that one interleaving loop can affect theother. (The same is true of loops executed by multiple threads.) </span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive690/pic1.gif" alt="" /><br /> Figure 1: IEnumerable class diagram </span></p>
<p><span class="smallblack">To overcome this problem, the IEnumerator&lt;t&gt;interfaces are not supported by the collection classes directly. Asshown in Figure 1, there is a second interface called IEnumerable&lt;t&gt; whose only method is GetEnumerator(). The purpose of this method is to return an object that supports IEnumerator&lt;t&gt;.Rather than the collection class maintaining the state itself, adifferent class, usually a nested class so that it has access to theinternals of the collection, will support the IEnumerator&lt;t&gt; interfaceand keep the state of the iteration loop. Using this pattern, the C#equivalent of a foreach loop will look like what&#39;s shown in Listing 4. &lt;/t&gt;&lt;/t&gt;&lt;/t&gt;&lt;/t&gt;</span></p>
<p><span class="smallblack">Listing 4: A separate enumerator maintains state during an iteration </span></p>
<p><span class="smallestblack"><span class="smallblack">System.Collections.Generic.Stack&lt;int&gt; stack =<br /> new System.Collections.Generic.Stack&lt;int&gt;();<br />int number;<br />System.Collections.Generic.Stack&lt;int&gt;.IEnumerator&lt;int&gt; enumerator;</p>
<p>// &#8230;<br />// If IEnumerable&lt;t&gt; is implemented explicitly, <br />// then a cast is required.<br />// ((IEnumerable)stack).GetEnumeraor();<br />enumerator = stack.GetEnumerator();<br />while (enumerator.MoveNext())<br />{<br /> number = enumerator.Current;<br /> Console.WriteLine(number);<br />}<br />&lt;/t&gt;&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;</span>
<p><span class="smallblack"><b>Error Handling</b></span></p>
<p><span class="smallblack">Since the classes that implement the IEnumerator&lt;t&gt;interface maintain the state, there are occasions when the state needscleaning up after all iterations have completed. To achieve this, theIEnumerator&lt;t&gt; interface derives from IDisposable. Enumerators thatimplement IEnumerator do not necessarily implement IDisposable, but ifthey do, Dispose() will be called as well. This enables the calling ofDispose() after the foreach loop exits. The C# equivalent of the finalCIL code, therefore, looks like Listing 5. <br />Listing 5: Compiled Result of foreach on Collections &lt;/t&gt;&lt;/t&gt;</span></p>
<p><span class="smallestblack"><span class="smallblack">System.Collections.Generic.Stack&lt;int&gt; stack =<br /> new System.Collections.Generic.Stack&lt;int&gt;();<br />int number;<br />System.Collections.Generic.Stack&lt;int&gt;.Enumerator&lt;int&gt; enumerator;<br />IDisposable disposable;<br />enumerator = stack.GetEnumerator();</p>
<p>try<br />{<br /> while (enumerator.MoveNext())<br /> {<br /> number = enumerator.Current;<br /> Console.WriteLine(number);<br /> }<br />}<br />finally<br />{<br /> // Explicit cast used for IEnumerator&lt;t&gt;.<br /> disposable = (IDisposable) enumerator;<br /> disposable.Dispose();</p>
<p> // IEnumerator will use the as operator unless IDisposable<br /> // support determinable at compile time.<br /> // disposable = (enumerator as IDisposable);<br /> // if (disposable != null)<br /> // {<br /> // disposable.Dispose();<br /> // }<br />}<br />&lt;/t&gt;&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;</span>
<p><span class="smallblack">Notice that because the IDisposable interface is supported by I<br />
Enumerat<br />
or&lt;t&gt;, the C# code can be simplified with the using keyword as shown in Listing 6. &lt;/t&gt;</span></p>
<p><span class="smallblack">Listing 6: Error handling and resource cleanup with using </span></p>
<p><span class="smallestblack"><span class="smallblack">System.Collections.Generic.Stack&lt;int&gt; stack =<br /> new System.Collections.Generic.Stack&lt;int&gt;();<br />int number;</p>
<p>using(<br /> System.Collections.Generic.Stack&lt;int&gt;.Enumerator&lt;int&gt; enumerator = <br /> stack.GetEnumerator())<br />{<br /> while (enumerator.MoveNext())<br /> {<br /> number = enumerator.Current;<br /> Console.WriteLine(number);<br /> }<br />}<br />&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;&lt;/int&gt;</span>
<p><span class="smallblack">However, recall that the using keyword is notdirectly supported by CIL either, so in reality the former code is amore accurate C# representation of the foreach CIL code. </span></p>
<p><span class="smallblack">Readers may recall that the compiler preventsassignment of the foreach variable identifier (number). As isdemonstrated in Listing 6, an assignment of number would not be achange to the collection element itself so rather than mistakenlyassume that, the C# compiler prevents such an assignment altogether. </span></p>
<p><span class="smallblack">In addition, the element count within acollection cannot be modified during the execution of a foreach loop.If, for example, we called stack.Push(42) inside the foreach loop, itwould be ambiguous whether the iterator should ignore or incorporatethe change to stack . should iterator iterate over the newly added itemor ignore it and assume the exact same state as when it wasinstantiated. </span></p>
<p><span class="smallblack">Because of this ambiguity, an exception oftype System.InvalidOperationException is thrown if the collection ismodified within a foreach loop, reporting that the collection wasmodified after the enumerator was instantiated. </span></p>
<p><span class="smallblack">(This content was largely taken from the Collections chapter of my book, Essential C# 2.0 [Addison-Wesley])</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/09/the-internals-of-c-foreach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance of Various Iteration Methods in .NET</title>
		<link>http://www.csharphelp.com/2007/02/performance-of-various-iteration-methods-in-net/</link>
		<comments>http://www.csharphelp.com/2007/02/performance-of-various-iteration-methods-in-net/#comments</comments>
		<pubDate>Thu, 08 Feb 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Looping]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=448</guid>
		<description><![CDATA[Introduction I?ve been implementing numerical librariesin .NET and have come to some conclusions about iteration performance.My classes have to hold a large amount of data and be able to iteratethrough that data as quickly as possible. In order to compare variousmethods, I created a simple class called Data that encapsulates anarray of doubles. Method #1: [...]]]></description>
			<content:encoded><![CDATA[<h2><span class="smallblack">Introduction</span></h2>
<p><span class="smallblack">I?ve been implementing numerical librariesin .NET and have come to some conclusions about iteration performance.My classes have to hold a large amount of data and be able to iteratethrough that data as quickly as possible. In order to compare variousmethods, I created a simple class called Data that encapsulates anarray of doubles. </span></p>
<h2><span class="smallblack">Method #1: Enumeration</span></h2>
<p><span class="smallblack">Data implements IEnumerable. It contains GetEnumerator which returns its own DataEnumerator, an inner class.</span></p>
<p><span class="smallblack">?<br /> public IEnumerator GetEnumerator() <br /> {<br /> return new DataEnumerator( this );<br /> }</p>
<p> internal class DataEnumerator : IEnumerator<br /> {<br /> private Data internal_ = null;<br /> private int index = -1;</p>
<p> public DataEnumerator( Data data ) <br /> {<br /> internal_ = data;<br /> }</p>
<p> public object Current<br /> {<br /> get<br /> {<br /> return internal_.Array[index];<br /> }<br /> }</p>
<p> public bool MoveNext()<br /> {<br /> index++;<br /> if ( index &gt;= internal_.Array.Length ) <br /> {<br /> return false;<br /> }<br /> return true;<br /> }</p>
<p> public void Reset()<br /> {<br /> index = -1;<br /> }<br /> }<br />?<br /></span><br />
<h2><span class="smallblack">Method #2: Indexing</span></h2>
<p><span class="smallblack">I implemented an index operator on the class which simply calls the index operator on the array.</span></p>
<p><span class="smallblack"> public double this[int position]<br /> {<br /> get<br /> {<br /> return array_[position];<br /> }<br /> }<br /></span><br />
<h2><span class="smallblack">Method #3: Indirect Array</span></h2>
<p><span class="smallblack">I created a property to access the array.</span></p>
<p><span class="smallblack"> public double[] Array<br /> {<br /> get <br /> {<br /> return array_;<br /> }<br /> }<br /></span>
<p><span class="smallblack">When iterating, I called the Array property and then its index operator.</span></p>
<p><span class="smallblack"> d = data.Array[j];<br /></span><br />
<h2><span class="smallblack">Method #3: Direct Array</span></h2>
<p><span class="smallblack">I created a reference to the array.</span></p>
<p><span class="smallblack"> double[] array = data.Array;<br /></span>
<p><span class="smallblack">Then, I iterate through that reference.</span></p>
<p><span class="smallblack"> d = array[j];<br /></span><br />
<h2><span class="smallblack">Method #4: Pointer Math</span></h2>
<p><span class="smallblack">Finally, I tried improving performance by iterating through the array in Managed C++ using pointer manipulation.</span></p>
<p><span class="smallblack"> static void iterate( Data&amp; data )<br /> {<br /> double d;<br /> double __pin* ptr = &amp;( data.Array[0] );<br /> for ( int i = 0; i &lt; data.Array.Length; i++ ) <br /> {<br /> d = *ptr;<br /> ++ptr;<br /> }<br /> }<br /></span>
<p><span class="smallblack">I called it this way:</span></p>
<p><span class="smallblack"> Pointer.iterate( data );<br /></span><br />
<h2><span class="smallblack">Conclusions</span></h2>
<p><span class="smallblack">To test the different methods, I allocated1,000,000 doubles into an array and indexed over all of them. Irepeated this 1,000 times to minimize randomness. Here are theresults&#8230;</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives2/files/archive465/Article.png" alt="Results" height="400" width="600" /></span></p>
<p><span class="smallblack">Enumeration is always slow. That?s notsurprising as I?m using a general data structure to hold the doubles.Each access performs a cast.The three operator/property methods differed very slightly. These areprobably all optimized similarly.Using pointer math to traverse over the raw data was significantlyfaster. This is probably due to the fact that there?s no boundschecking.In summary, if you have large amounts of data and performance iscritical, consider using managed C++.</span></p>
<h3><span class="smallblack">Acknowledgements</span></h3>
<p><span class="smallblack">Thanks to Mark Vulfson of <a href="http://www.proworks.com/">ProWorks</a> for tips on using Flipper Graph Control. Also, to my colleagues Ken Baldwin and Steve Sneller at <a href="http://www.centerspace.net/">CenterSpace Software</a>.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/02/performance-of-various-iteration-methods-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio .Net Macros for Quick Insertion of C# Conditional and Iteration Statements</title>
		<link>http://www.csharphelp.com/2006/07/visual-studio-net-macros-for-quick-insertion-of-c-conditional-and-iteration-statements/</link>
		<comments>http://www.csharphelp.com/2006/07/visual-studio-net-macros-for-quick-insertion-of-c-conditional-and-iteration-statements/#comments</comments>
		<pubDate>Wed, 12 Jul 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Other]]></category>
		<category><![CDATA[Looping]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=237</guid>
		<description><![CDATA[&#160; To use, open Macro Explorer and copy and pasteinto an existing or new macro project. To run a macro place the cursorat the required insertion point in your document and double-click thename of the macro in Macro Explorer. You may wish to define moreconvenient keyboard shortcuts for each macro via the Tools &#124; Customizemenu. [...]]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:kevin@atech.globalnet.co.uk"></a></span></p>
<p><span class="smallblack"><a href="mailto:kevin@atech.globalnet.co.uk"></a></span></p>
<p><span class="smallblack">To use, open Macro Explorer and copy and pasteinto an existing or new macro project. To run a macro place the cursorat the required insertion point in your document and double-click thename of the macro in Macro Explorer. You may wish to define moreconvenient keyboard shortcuts for each macro via the Tools | Customizemenu. </span></p>
<p><span class="smallblack">Imports EnvDTE<br />Imports System.Diagnostics</p>
<p>Public Module CSharp<br /> &#39; Description: Inserts for loop<br /> Sub ForLoop()<br /> DTE.ActiveDocument.Selection.Text = &quot;for (int i = 0; i &lt; ; i++)&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 3)<br /> DTE.ActiveDocument.Selection.CharRight(False, 19)<br /> End Sub</p>
<p> &#39; Description: Inserts while loop<br /> Sub WhileLoop()<br /> DTE.ActiveDocument.Selection.Text = &quot;while ()&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 3)<br /> DTE.ActiveDocument.Selection.CharRight(False, 6)<br /> End Sub</p>
<p> &#39; Description: Inserts do-while loop<br /> Sub DoWhileLoop()<br /> DTE.ActiveDocument.Selection.Text = &quot;do&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;} while ();&quot;<br /> DTE.ActiveDocument.Selection.CharLeft(False, 2)<br /> End Sub</p>
<p> &#39; Description: Inserts foreach loop<br /> Sub ForEach()<br /> DTE.ActiveDocument.Selection.Text = &quot;foreach ( in )&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 3)<br /> DTE.ActiveDocument.Selection.CharRight(False, <img src='http://www.csharphelp.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> <br /> End Sub</p>
<p> &#39;Description: Inserts if block<br /> Sub IfNoElse()<br /> DTE.ActiveDocument.Selection.Text = &quot;if ()&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 3)<br /> DTE.ActiveDocument.Selection.CharRight(False, 3)<br /> End Sub</p>
<p> &#39; Description: Inserts if-else block<br /> Sub IfElse()<br /> DTE.ActiveDocument.Selection.Text = &quot;if ()&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;else&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 7)<br /> DTE.ActiveDocument.Selection.CharRight(False, 3)<br /> End Sub</p>
<p> &#39; Description: Inserts switch block<br /> Sub Switch()<br /> DTE.ActiveDocument.Selection.Text = &quot;switch ()&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;case :&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;break;&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;case :&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;break;&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;default:&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;break;&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, <img src='http://www.csharphelp.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> <br /> DTE.ActiveDocument.Selection.CharRight(False, 7)<br /> End Sub</p>
<p> &#39; Description: Inserts generic exception block<br /> Sub Exception()<br /> DTE.ActiveDocument.Selection.Text = &quot;try&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;catch (System.Exception ex)&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;{&quot;<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.NewLine()<br /> DTE.ActiveDocument.Selection.Text = &quot;}&quot;<br /> DTE.ActiveDocument.Selection.LineUp(False, 5)<br /> End Sub</p>
<p>End Module<br /></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/07/visual-studio-net-macros-for-quick-insertion-of-c-conditional-and-iteration-statements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Your Own C# Enumerator To Use With The foreach Construct</title>
		<link>http://www.csharphelp.com/2006/05/building-your-own-c-enumerator-to-use-with-the-foreach-construct/</link>
		<comments>http://www.csharphelp.com/2006/05/building-your-own-c-enumerator-to-use-with-the-foreach-construct/#comments</comments>
		<pubDate>Fri, 12 May 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Looping]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=176</guid>
		<description><![CDATA[We are going to use &#34;foreach&#34; to iterate through our collection of fruit objects. Lets assume that we have a class called Fruitwhich contains the fields; string name ,int num and bool ripe. We builda class called Fruits which represents a collection of fruit objects. public class Fruits{ //we don?t have to specify private as [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:richard@saiba.co.uk"></a></span></p>
<p><span class="smallblack">We are going to use &quot;foreach&quot; to iterate through our collection of fruit objects.</span></p>
<p><span class="smallblack">Lets assume that we have a class called Fruitwhich contains the fields; string name ,int num and bool ripe. We builda class called Fruits which represents a collection of fruit objects.</span></p>
<p><span class="smallblack">public class Fruits<br />{<br /> //we don?t have to specify private as this is the default modifier<br /> //it?s just included to highlight the fact that this is private to<br /> //the Fruits collection. </p>
<p> private Fruit[] fruitArray; </p>
<p> //Create a basket of fruit </p>
<p> public Fruits()<br /> {<br /> fruitArray = new Fruit[3];<br /> fruitArray[0] = new Fruit(&quot;Banana&quot;,false,3);<br /> fruitArray[1] = new Fruit(&quot;Apples&quot;,true,5);<br /> fruitArray[2] = new Fruit(&quot;Oranges&quot;,true,3);<br /> }<br />}<br /></span>
<p><span class="smallblack">In order to obtain each Fruit from the Fruitscollection it would be convenient if the object user could iterate overthe Fruits type using the foreach construct. It would be reasonable tocode:</span></p>
<p><span class="smallblack">public class FruitBar<br />{<br /> public static void Main()<br /> {<br /> Fruits fruitbasket = new Fruits();<br /> //Show only the ripe fruit<br /> foreach (Fruit f in fruitbasket)<br /> {<br /> if (f.ripe == true)<br /> {<br /> Console.WriteLine(&quot;Name : {0}&quot;,f.name);<br /> Console.WriteLine(&quot;Amount : {0}&quot;,f.num); <br /> }<br /> { <br /> }<br />} <br /></span>
<p><span class="smallblack">Unfortunately attempting to execute this code results in the compiler complaining that it cannot find GetEnumerator.</span></p>
<p><span class="smallblack">To use the foreach syntax your class mustsupport the IEnumerable interface found in the System.Collectionsnamespace. IEnumerable defines only one method, public IEnumeratorGetEnumerator(), notice that this method returns another interfaceIEnumerator also found in System.Collections namespace.</span></p>
<p><span class="smallblack">IEnumerator supports a simple iteration over a collection. It publishes two methods and a property:</span></p>
<p><span class="smallblack">bool MoveNext():<br />Advances the enumerator tothe next element in the collection. Returns true if successfullyadvanced to the next element in the collection and false if the movewould take it beyond the last element.</span></p>
<p><span class="smallblack">void Reset():<br />Sets the enumerator to the initial position, which is before the first element in the collection (-1)</span></p>
<p><span class="smallblack">object Current {get;}:<br />Gets the current element in the collection. Throws Exception Type InvalidOperationException.</span></p>
<p><span class="smallblack">To successfully implement an enumerator wemust keep in mind the following protocol. After an enumerator iscreated or after a Reset, MoveNext must be called to advance theenumerator to the first element of the collection before reading thevalue of Current. Current throws an exception if the last call toMoveNext returns false. Current does not move the position of theenumerator.</span></p>
<p><span class="smallblack">This is by no means a thorough discussion on implementing enumeration, more an introduction to using enumerators with foreach.</span></p>
<p><span class="smallblack">Here is an example of the changes required to implement an enumerator for use with the foreach construct.</span></p>
<p><span class="smallblack">namespace MyFruitBasket<br />{<br /> public class Fruit<br /> {<br /> //this is a bad way to declare fields in a class<br /> //but this is just an example <br /> public string name;<br /> public bool ripe;<br /> public int num;</p>
<p> public Fruit(string nme, bool rp, int n)<br /> {<br /> name = nme;<br /> ripe = rp;<br /> num = n;<br /> }<br /> }<br /></span>
<p><span class="smallblack">The Fruits collection implements the IEnumerable and IEnumerator interfaces.</span></p>
<p><span class="smallblack">public class Fruits :IEnumerable,IEnumerator<br />{<br /> Fruit[] fruitArray;<br /> //current position in array set to initial position<br /> int position = -1;<br /> //Create a basket of fruit <br /> public Fruits()<br /> {<br /> fruitArray = new Fruit[3];<br /> fruitArray[0] = new Fruit(&quot;Banana&quot;,false,3);<br /> fruitArray[1] = new Fruit(&quot;Apples&quot;,true,5);<br /> fruitArray[2] = new Fruit(&quot;Oranges&quot;,true,3);<br /> }</p>
<p> //Implement IEnumerable</p>
<p> public IEnumerator GetEnumerator()<br /> {<br /> return (IEnumerator)this;<br /> }</p>
<p> //Implement IEnumerator<br /> public bool MoveNext()<br /> {<br /> position++;<br /> if (position &lt; fruitArray.Length)<br /> {<br /> return true;<br /> }<br /> else<br /> {<br /> return false;<br /> }<br /> }<br /> public void Reset()<br /> {<br /> position = -1;<br /> }<br /> public object Current<br /> {<br /> get{return fruitArray[position];}<br /> }<br />}</p>
<p>class FruitBar<br />{<br /> static void Main(string[] args)<br /> {<br /> Fruits fruitbasket = new Fruits();<br /> //Present only the ripe fruit<br /> foreach (Fruit f in fruitbasket)<br /> { <br /> if (f.ripe == true)<br /> Console.WriteLine(&quot;Name : {0}&quot;,f.name);<br /> Console.WriteLine(&quot;Amount : {0}&quot;,f.num); <br /> } <br /> string x = Console.ReadLine();<br /> }<br /> }<br />}<br /></span>
<p><span class="smallblack">I hope this has been of some help.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/05/building-your-own-c-enumerator-to-use-with-the-foreach-construct/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

