<?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>Chicken Scratches &#187; C#</title>
	<atom:link href="http://www.chickenwingsw.com/scratches/category/c/feed" rel="self" type="application/rss+xml" />
	<link>http://www.chickenwingsw.com</link>
	<description>Developing ideas on developing.</description>
	<lastBuildDate>Thu, 01 Apr 2010 17:24:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>When to use ToArray()</title>
		<link>http://www.chickenwingsw.com/scratches/programming/when-to-use-toarray</link>
		<comments>http://www.chickenwingsw.com/scratches/programming/when-to-use-toarray#comments</comments>
		<pubDate>Mon, 11 Feb 2008 20:06:51 +0000</pubDate>
		<dc:creator>Eddie Sullivan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.chickenwingsoftware.com/scratches/programming/when-to-use-toarray</guid>
		<description><![CDATA[Some thoughts on when to return a List<> object and when to return an array in .NET.]]></description>
			<content:encoded><![CDATA[    <p>
      Some thoughts on when to return a <span class="type">List&lt;&gt;</span> object and when to return
    an array in C#.
    </p>

    <h4>The analogy: strings</h4>

    <p>
      Many times in C#, a function that needs to build a string from
      constituent parts will use a <span class="type">StringBuilder</span> internally, and then
      on the last line of the function call ToString() on the
      <span class="type">StringBuilder</span> object. This is because strings in C# are
      immutable. That is, once they are set then can never be
      changed. Code that looks like it is changing a string in place
      is usually actually allocating a new string to hold the new
      value. Obviously, for a function that builds a string
      incrementally by constantly appending to it, this can lead to
      lots of reallocation, slowing down performance.
    </p>
    <p>
      Here's an example of how it's normally done:
    </p>
    <pre>
    <span class="keyword">public</span> <span class="type">string</span> <span class="function-name">GimmeString</span>(<span class="type">int</span> <span class="variable-name">num</span>)
    {
        <span class="type">StringBuilder</span> <span class="variable-name">sb</span> = <span class="keyword">new</span> <span class="type">StringBuilder</span>("<span class="string">Initiating countdown: </span>");

        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable-name">i</span> = num; i &gt; 0; i--)
        {
            <span class="reference">sb</span>.Append(<span class="reference">string</span>.Format("<span class="string">{0}...</span>", i));
        }
        <span class="reference">sb</span>.Append("<span class="string">Blastoff!\n</span>");

        <span class="keyword">return</span> <span class="reference">sb</span>.ToString();
    }
    </pre>
    <p>
      This is a pretty obvious design pattern. It's rare you would
      want to return the <span class="type">StringBuilder</span> object itself, so almost always
      it is converted to a string before returning. The problem gets
      trickier, however, when we try to use a similar design pattern
      for arrays.
    </p>

    <h4>Arrays</h4>
    <p>
      Arrays in C# are not immutable, at least not in the way strings
      are. It could be said they are "partially immutable" (my own
      made-up term). You can swap out elements in the array as much as
      you like, but the array's length is fixed. Therefore, if you
      need to build up an array from constituent parts, it makes sense
      to use a <span class="type">List&lt;&gt;</span> object for doing
      the work.
    </p>
    <p>
      The analogy then becomes, in SAT terms:
    </p>
    <pre><span class="type">StringBuilder</span> : string :: <span class="type">List&lt;&gt;</span> : array</pre>
    <p>
 The question then
      becomes whether or not to call ToArray() on the <span class="type">List&lt;&gt;</span> before returning
      it. In this case, the answer's not as obvious. Let's examine the
      pros and cons of each approach:
    </p>
    <h4>Reasons to call ToArray()</h4>
    <ul>
      <li>
	If the returned value is not meant to be modified, returning
	it as an array makes that fact a bit clearer.
      </li>
      <li>
	If the caller is expected to perform many non-sequential
	accesses to the data, there can be a performance benefit to an
	array over a <span class="type">List&lt;&gt;</span>.
      </li>
      <li>
	If you know you will need to pass the returned value to a
	third-party function that expects an array.
      </li>
      <li>
	Compatibility with calling functions that need to work with
	.NET version 1 or 1.1. These versions don't have the <span class="type">List&lt;&gt;</span> type (or any generic types, for
	that matter).
      </li>
    </ul>

    <h4>Reasons not to call ToArray()</h4>
    <ul>
      <li>
	If the caller ever <em>does</em> need to add or remove
	elements, a <span class="type">List&lt;&gt;</span> is absolutely required.
      </li>
      <li>
	The performance benefits are not necessarily guaranteed,
	especially if the caller is accessing the data in a sequential
	fashion. There is also the additional step of converting from
	<span class="type">List&lt;&gt;</span> to array, which takes processing time.
      </li>
      <li>
	The caller can always convert the list to an array themselves.
      </li>
    </ul>

    <h4>ToArray() or not ToArray()? That is the question.</h4>
    <p>
      Based on these points, it seems to make the most sense as a
      general rule to simply return the <span class="type">List&lt;&gt;</span> object directly, rather than
      converting it to an array before returning. Let me know if you
      disagree.
    </p>
    <p>
      Here's an example:
    </p>

    <pre>
    <span class="comment">// A contrived example. Similar to Python's "range" function, but only
</span>    <span class="comment">// supports positive step.
</span>    <span class="keyword">public</span> <span class="type">List&lt;int&gt;</span> GimmeInts(<span class="type">int</span> <span class="variable-name">start</span>, <span class="type">int</span> <span class="variable-name">end</span>, <span class="type">int</span> <span class="variable-name">step</span>)
    {
        List&lt;<span class="type">int</span>&gt; ret = <span class="keyword">new</span> <span class="type">List</span>&lt;<span class="type">int</span>&gt;();

        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable-name">i</span> = start; i &lt; end; i += step)
        {
            <span class="reference">ret</span>.Add(i);
        }
        <span class="comment">// Here you could have:
</span>        <span class="comment">// return ret.ToArray();
</span>        <span class="keyword">return</span> ret;
    }
    </pre>
]]></content:encoded>
			<wfw:commentRss>http://www.chickenwingsw.com/scratches/programming/when-to-use-toarray/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
