<?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>dotnet Archives - Yumasoft</title>
	<atom:link href="https://blog.yumasoft.pl/tag/dotnet/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.yumasoft.pl/tag/dotnet/</link>
	<description>Software development blog</description>
	<lastBuildDate>Mon, 30 Aug 2021 04:02:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.yumasoft.pl/wp-content/uploads/2021/05/cropped-yumasoft_icon_transparent-32x32.png</url>
	<title>dotnet Archives - Yumasoft</title>
	<link>https://blog.yumasoft.pl/tag/dotnet/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Foreach, IEnumerable and IEnumerator in C#</title>
		<link>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/</link>
					<comments>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 06 Sep 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dotnet]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=593</guid>

					<description><![CDATA[<p>Today, we&#8217;re taking a deeper look at foreach loop in C#. What does a collection need to be able to use it in a foreach loop? Does it have to implement IEnumerable interface? These questions are often asked during interviews, so it&#8217;s worth knowing the answers ? We will go through a step-by-step example in&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/">Foreach, IEnumerable and IEnumerator in C#</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Today, we&#8217;re taking a deeper look at <code>foreach</code> loop in C#. What does a collection need to be able to use it in a <code>foreach</code> loop? Does it have to implement <code>IEnumerable</code> interface? These questions are often asked during interviews, so it&#8217;s worth knowing the answers ?</p>



<p>We will go through a step-by-step example in building our own custom collection to see how all that works. Let&#8217;s dive in! ?</p>



<span id="more-593"></span>



<p><em>Throughout this article, I&#8217;m working with a Unit Tests project using .NET 5, C# 9.0 and <a href="https://nunit.org/">NUnit</a>. It makes it easier to play with the code on your own. We can create our custom collection and at the same time try it out in a <code>foreach</code> loop in a test method. I recommend this approach for testing out various programming concepts for yourself ?</em></p>



<h2 class="wp-block-heading">Custom collection implementing IEnumerable&lt;T&gt;</h2>



<p>First, we want to implement our own, custom collection in C#. The most obvious solution is to implement <code>IEnumerable&lt;T></code> interface. Our IDE will require our class to implement <code>IEnumerator GetEnumerator()</code> and <code>IEnumerator IEnumerable.GetEnumerator()</code> methods, so let&#8217;s do that:</p>



<script src="https://gist.github.com/dsibinski/f40065534bf002dbdce0e834db636d3c.js"></script>



<p>Of course, this is just an example to satisfy the <code>foreach</code> loop, so we won&#8217;t care about the actual implementation of these methods ?</p>



<p>Custom collection implemented in such a way can be used in <code>foreach</code> loop: </p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-599" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1-300x180.png 300w" sizes="(max-width: 444px) 100vw, 444px" /></figure></div>



<h2 class="wp-block-heading">Does foreach require IEnumerable?</h2>



<p>Let&#8217;s try to get rid of implementing <code>IEnumerable</code> interface. As soon as we do it, our IDE complains:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img decoding="async" width="856" height="394" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable.png" alt="Custom collection not implement IEnumerable and IDE complaining about &quot;IEnumerable.GetEnumerator&quot; method" class="wp-image-600" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable.png 856w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable-300x138.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable-768x353.png 768w" sizes="(max-width: 856px) 100vw, 856px" /></figure></div>



<p>Let&#8217;s try to remove <code>IEnumerable.GetEnumerator()</code> method completely, so our custom collection looks as follows:</p>



<script src="https://gist.github.com/dsibinski/af9b9f9b308e471652f2dcd754754bc6.js"></script>



<p>Now guess what &#8211; we can still use <code>MyCollection</code> within the <code>foreach</code> loop!</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-601" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method-300x180.png 300w" sizes="(max-width: 444px) 100vw, 444px" /></figure></div>



<p>So you already know that, when asked during an interview whether <code>foreach</code> needs a collection to implement <code>IEnumerable</code>, the answer is no ?</p>



<h2 class="wp-block-heading">Custom IEnumerator</h2>



<p>Currently, our collection has a single <code>GetEnumerator()</code> method returning <code>IEnumerator&lt;MyObject></code>. We already know that this method is needed in a collection to be able to use it within a <code>foreach</code> loop. </p>



<p>However, let&#8217;s work on what this method returns. We&#8217;ll implement our custom <code>IEnumerator</code>. Again &#8211; the most obvious solution is to create a class implementing <code>IEnumerator&lt;T></code> interface:</p>



<script src="https://gist.github.com/dsibinski/014116fc47bf9159dcfe3e44bb54b6fe.js"></script>



<p>That&#8217;s the implementation proposed by the IDE (Rider). We can now change our collection to use this custom enumerator. See that it can still be used within <code>foreach</code>:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="467" height="466" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator.png" alt="Custom collection (without implementing any interface) returns a custom enumerator MyObjectEnumerator" class="wp-image-603" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator.png 467w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator-300x300.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator-150x150.png 150w" sizes="auto, (max-width: 467px) 100vw, 467px" /></figure></div>



<p>So far, so good. But why all these methods in <code>MyObjectEnumerator</code>? ?</p>



<h2 class="wp-block-heading">Does foreach need an enumerator implementing IEnumerator?</h2>



<p>If we remove inheritance from <code>IEnumerator</code> from <code>MyObjectEnumerator</code>, the IDE only complains about <code>IEnumerator.Current</code> property, so let&#8217;s get rid of it. Our custom enumerator now looks as follows:</p>



<script src="https://gist.github.com/dsibinski/bb9e8ef54834656d4994e337c00f6c8a.js"></script>



<p>Yeah, you guessed it again &#8211; we can still use our collection in a <code>foreach</code> loop ?</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-604" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface-300x180.png 300w" sizes="auto, (max-width: 444px) 100vw, 444px" /></figure></div>



<p>However&#8230; Does our custom enumerator really needs all of these stuff:  <code>MoveNext(), Reset()</code>, <code>Dispose()</code> and <code>MyObject Current</code> ? Let&#8217;s remove all of them and see what our IDE tells us:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="517" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-1024x517.png" alt="IDE (JetBrains Rider) error:
Type 'ForeachFun.MyCollection' cannot be used in 'foreach' statement because it neither implements 'IEnumerable' or 'IEnumerable', nor has suitable 'GetEnumerator' method which return type has 'Current' property and 'MoveNext' method" class="wp-image-605" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-1024x517.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-300x151.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-768x388.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error.png 1153w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>That&#8217;s the error from IDE when trying to iterate through our custom collection in <code>foreach</code>:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p></p><cite>Type &#8216;ForeachFun.MyCollection&#8217; cannot be used in &#8216;foreach&#8217; statement because it neither implements &#8216;IEnumerable&#8217; or &#8216;IEnumerable&#8217;, <strong>nor has suitable &#8216;GetEnumerator&#8217; method which return type has &#8216;Current&#8217; property and &#8216;MoveNext&#8217; method</strong></cite></blockquote>



<p>This error actually tells us everything. This is the ultimate answer to the legendary C# interview question: &#8220;What does a collection need to be able to use it in <code>foreach</code> loop?&#8221;. In other words: &#8220;Is it necessary for a collection to implement <code>IEnumerable</code> to use it in a <code>foreach</code> loop?&#8221;</p>



<p>The answer is:<strong> a collection needs to have a <code>GetEnumerator</code>() method returning an object of type having <code>Current</code> property and <code>bool MoveNext()</code> method. No interfaces are required anywhere here ?</strong></p>



<p>The compiler uses duck typing to find these two necessary ingredients of the type returned from <code>GetEnumerator()</code>. It means that is looks for these properties by text. Later, depending on the type of <code>Current</code> property, a single element inside the <code>foreach</code> is typed accordingly. Only if this duck searching fails, the compiler checks whether the collection implements the interfaces.</p>



<p>In the end, this is our simplest and fully legit code (except the actual implementations of the methods, which is out of scope of this article):</p>



<script src="https://gist.github.com/dsibinski/99a2559ef72c2f493a231dc13879b4ec.js"></script>



<h2 class="wp-block-heading">Summary</h2>



<p>I hope you got to know something new about <code>foreach</code> loop from this article. This may not sound like a knowledge you&#8217;d need on a daily basis, but it&#8217;s worth knowing how stuff works under the hood ? Plus, you can always score a point during your next interview ?!</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/">Foreach, IEnumerable and IEnumerator in C#</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
