<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>VibrantCode - Code Oddities</title>
    <link>http://blog.andrewnurse.net/</link>
    <description>Oooh...pretty code</description>
    <language>en-us</language>
    <copyright>Andrew Nurse</copyright>
    <lastBuildDate>Mon, 02 Feb 2009 22:46:13 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.0.7226.0</generator>
    <managingEditor>andrew@andrewnurse.net</managingEditor>
    <webMaster>andrew@andrewnurse.net</webMaster>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=3de21807-e19b-4541-a7d7-aadef6944140</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,3de21807-e19b-4541-a7d7-aadef6944140.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,3de21807-e19b-4541-a7d7-aadef6944140.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=3de21807-e19b-4541-a7d7-aadef6944140</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I recently used the ‘yield’ keyword in a C# method and ran into a strange issue when
trying to verify arguments.  I always try to verify the arguments provided to
my methods so that I can throw <code>ArgumentException</code> or <code>ArgumentNullException</code> as
necessary.  However, when you use the ‘yield’ keyword to create an enumerator
in C#, you can run into issues
</p>
        <p>
The ‘yield’ keyword lets you easily create a method which returns an enumerator (which
can then be used in a <code>foreach</code> loop).  For example, if I wanted to
make a method that took a <code>DirectoryInfo</code> (representing a directory on
disk) and returned file names of all the .txt files in it, I would write this:
</p>
        <pre class="csharp" name="code">public IEnumerable&lt;string&gt; GetTextFiles(DirectoryInfo dir) {
    if (dir == null) {
        throw new ArgumentNullException("dir");
    }
    foreach (FileInfo file in dir.GetFiles("*.txt")) {
        yield return file.Name;
    }
}</pre>
        <p>
However, the C# compiler will do something tricky with this method, because of the
'yield' keyword.  It will create a custom implementation of <code>IEnumerable&lt;string&gt;</code> class
that uses "magic" (I'm not going to go into detail as to how it works :P)
to jump in and out of the code you wrote. Then, it compiles our method to the following
(as decompiled with <a href="http://www.red-gate.com/products/reflector/" target="_blank">RedGate's
.Net Reflector</a>, a free tool every .Net developer <strong>must</strong> have :D):
</p>
        <pre class="csharp" name="code">public IEnumerable&lt;string&gt; GetTextFiles(DirectoryInfo dir)
{
    &lt;GetTextFiles&gt;d__0 d__ = new &lt;GetTextFiles&lt;d__0(-2);
    d__.&lt;&gt;4__this = this;
    d__.&lt;&gt;3__dir = dir;
    return d__;
}</pre>
        <p>
Wait a sec, where'd our code go?  It looks like it’s gone into this <code>&lt;GetTextFiles&gt;d__0</code> class. 
If you think that name sounds compiler-generated, you’re right!  It’s the custom
implementation of <code>IEnumerable&lt;string&gt;</code> that was created by the compiler. 
Cool, eh?  However, there’s a side effect here.  Where did our argument
checking code go?  Unless there’s something in the <code>&lt;GetTextFiles&gt;d__0</code> constructor,
the user could pass <code>null</code> in for the <code>dir</code> parameter and no
exception would be thrown!  So, let’s take a look at the <code>&lt;GetTextFiles&gt;d__0</code> constructor
(using Reflector again):
</p>
        <pre class="csharp" name="code">[DebuggerHidden]
public &lt;GetTextFiles&gt;d__0(int &lt;&gt;1__state)
{
    this.&lt;&gt;1__state = &lt;&gt;1__state;
    this.&lt;&gt;l__initialThreadId = Thread.CurrentThread.ManagedThreadId;
}</pre>
        <p>
Nope, nothing there.  If you keep checking around the <code>&lt;GetTextFiles&gt;d__0</code> class,
you’ll find it in the <code>MoveNext</code> method on that class.  That means
that instead of checking the argument when you call the method, the argument won’t
be checked until the first time <code>MoveNext</code> is called (i.e. the first iteration
of a foreach loop).  If, instead, we wrap the actual “yield” code in it’s own
method, and call it from our original method (after argument checks), we’ll get the
desired result:
</p>
        <pre>public IEnumerable&lt;string&gt; GetTextFiles(DirectoryInfo dir) {
    if (dir == null) {
        throw new ArgumentNullException("dir");
    }
    return InternalGetTextFiles(dir);
}
private IEnumerable&lt;string&gt; InternalGetTextFiles(DirectoryInfor dir) {
    foreach (FileInfo file in dir.GetFiles("*.txt")) {
        yield return file.Name;
    }
}</pre>
        <p>
Now, the "magic" is occurring in <code>InternalGetTextFiles</code> and <code>GetTextFiles</code> is
compiled without modification and our argument checking works just fine.
</p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=3de21807-e19b-4541-a7d7-aadef6944140" />
      </body>
      <title>Argument check gotcha with &amp;lsquo;yield&amp;rsquo; keyword in C#</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,3de21807-e19b-4541-a7d7-aadef6944140.aspx</guid>
      <link>http://blog.andrewnurse.net/2009/02/02/ArgumentCheckGotchaWithLsquoyieldrsquoKeywordInC.aspx</link>
      <pubDate>Mon, 02 Feb 2009 22:46:13 GMT</pubDate>
      <description>&lt;p&gt;
I recently used the ‘yield’ keyword in a C# method and ran into a strange issue when
trying to verify arguments.&amp;#160; I always try to verify the arguments provided to
my methods so that I can throw &lt;code&gt;ArgumentException&lt;/code&gt; or &lt;code&gt;ArgumentNullException&lt;/code&gt; as
necessary.&amp;#160; However, when you use the ‘yield’ keyword to create an enumerator
in C#, you can run into issues
&lt;/p&gt;
&lt;p&gt;
The ‘yield’ keyword lets you easily create a method which returns an enumerator (which
can then be used in a &lt;code&gt;foreach&lt;/code&gt; loop).&amp;#160; For example, if I wanted to
make a method that took a &lt;code&gt;DirectoryInfo&lt;/code&gt; (representing a directory on
disk) and returned file names of all the .txt files in it, I would write this:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public IEnumerable&amp;lt;string&amp;gt; GetTextFiles(DirectoryInfo dir) {
    if (dir == null) {
        throw new ArgumentNullException(&amp;quot;dir&amp;quot;);
    }
    foreach (FileInfo file in dir.GetFiles(&amp;quot;*.txt&amp;quot;)) {
        yield return file.Name;
    }
}&lt;/pre&gt;
&lt;p&gt;
However, the C# compiler will do something tricky with this method, because of the
'yield' keyword.&amp;#160; It will create a custom implementation of &lt;code&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/code&gt; class
that uses &amp;quot;magic&amp;quot; (I'm not going to go into detail as to how it works :P)
to jump in and out of the code you wrote. Then, it compiles our method to the following
(as decompiled with &lt;a href="http://www.red-gate.com/products/reflector/" target="_blank"&gt;RedGate's
.Net Reflector&lt;/a&gt;, a free tool every .Net developer &lt;strong&gt;must&lt;/strong&gt; have :D):
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public IEnumerable&amp;lt;string&amp;gt; GetTextFiles(DirectoryInfo dir)
{
    &amp;lt;GetTextFiles&amp;gt;d__0 d__ = new &amp;lt;GetTextFiles&amp;lt;d__0(-2);
    d__.&amp;lt;&amp;gt;4__this = this;
    d__.&amp;lt;&amp;gt;3__dir = dir;
    return d__;
}&lt;/pre&gt;
&lt;p&gt;
Wait a sec, where'd our code go?&amp;#160; It looks like it’s gone into this &lt;code&gt;&amp;lt;GetTextFiles&amp;gt;d__0&lt;/code&gt; class.&amp;#160;
If you think that name sounds compiler-generated, you’re right!&amp;#160; It’s the custom
implementation of &lt;code&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/code&gt; that was created by the compiler.&amp;#160;
Cool, eh?&amp;#160; However, there’s a side effect here.&amp;#160; Where did our argument
checking code go?&amp;#160; Unless there’s something in the &lt;code&gt;&amp;lt;GetTextFiles&amp;gt;d__0&lt;/code&gt; constructor,
the user could pass &lt;code&gt;null&lt;/code&gt; in for the &lt;code&gt;dir&lt;/code&gt; parameter and no
exception would be thrown!&amp;#160; So, let’s take a look at the &lt;code&gt;&amp;lt;GetTextFiles&amp;gt;d__0&lt;/code&gt; constructor
(using Reflector again):
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;[DebuggerHidden]
public &amp;lt;GetTextFiles&amp;gt;d__0(int &amp;lt;&amp;gt;1__state)
{
    this.&amp;lt;&amp;gt;1__state = &amp;lt;&amp;gt;1__state;
    this.&amp;lt;&amp;gt;l__initialThreadId = Thread.CurrentThread.ManagedThreadId;
}&lt;/pre&gt;
&lt;p&gt;
Nope, nothing there.&amp;#160; If you keep checking around the &lt;code&gt;&amp;lt;GetTextFiles&amp;gt;d__0&lt;/code&gt; class,
you’ll find it in the &lt;code&gt;MoveNext&lt;/code&gt; method on that class.&amp;#160; That means
that instead of checking the argument when you call the method, the argument won’t
be checked until the first time &lt;code&gt;MoveNext&lt;/code&gt; is called (i.e. the first iteration
of a foreach loop).&amp;#160; If, instead, we wrap the actual “yield” code in it’s own
method, and call it from our original method (after argument checks), we’ll get the
desired result:
&lt;/p&gt;
&lt;pre&gt;public IEnumerable&amp;lt;string&amp;gt; GetTextFiles(DirectoryInfo dir) {
    if (dir == null) {
        throw new ArgumentNullException(&amp;quot;dir&amp;quot;);
    }
    return InternalGetTextFiles(dir);
}
private IEnumerable&amp;lt;string&amp;gt; InternalGetTextFiles(DirectoryInfor dir) {
    foreach (FileInfo file in dir.GetFiles(&amp;quot;*.txt&amp;quot;)) {
        yield return file.Name;
    }
}&lt;/pre&gt;
&lt;p&gt;
Now, the &amp;quot;magic&amp;quot; is occurring in &lt;code&gt;InternalGetTextFiles&lt;/code&gt; and &lt;code&gt;GetTextFiles&lt;/code&gt; is
compiled without modification and our argument checking works just fine.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=3de21807-e19b-4541-a7d7-aadef6944140" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,3de21807-e19b-4541-a7d7-aadef6944140.aspx</comments>
      <category>CMPT 376</category>
      <category>Code Oddities</category>
      <category>Tips</category>
    </item>
  </channel>
</rss>