<?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>out &#62;&#62; m_Conscientia; &#187; Application Development Foundation</title>
	<atom:link href="http://blog.hypercomplex.co.uk/index.php/tag/application-development-foundation/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hypercomplex.co.uk</link>
	<description>a multidimensional braindump</description>
	<lastBuildDate>Mon, 02 Aug 2010 22:30:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Sorting</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/09/sorting/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/09/sorting/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 21:18:34 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[IComparer]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=476</guid>
		<description><![CDATA[In the .NET 1.1 era, sorting is based on the IComparer and IComparable interfaces. I first realised this scheme is a little limited in a job interview. I tried to explain how I might sort a contact list on different properties. In my mind I envisaged something similar to the STL sort algorithm using a [...]]]></description>
			<content:encoded><![CDATA[<p>In the .NET 1.1 era, sorting is based on the <a href="http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx">IComparer</a> and <a href="http://msdn.microsoft.com/en-us/library/system.icomparable.aspx">IComparable</a> interfaces. I first realised this scheme is a little limited in a job interview. I tried to explain how I might sort a contact list on different properties. In my mind I envisaged something similar to the <a href="http://www.cplusplus.com/reference/algorithm/sort/">STL sort algorithm</a> using a function pointer or <a href="http://en.wikipedia.org/wiki/Function_object">functor</a>. Unfortunately, at the time I was unable to express this in C#.</p>
<p>Let&#8217;s say our Contact data structure is simply this:</p>

<div class="wp_codebox"><table><tr id="p4768"><td class="code" id="p476code8"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Contact <span style="color: #008000;">:</span> IComparable
<span style="color: #008000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">// constructor omitted, just assume it assigns fields</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Forename <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Surname <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> PhoneNo <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> EmailAddress <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> CompareTo<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> obj<span style="color: #008000;">&#41;</span> 
   <span style="color: #008000;">&#123;</span>
        Contact otherContact <span style="color: #008000;">=</span> obj <span style="color: #0600FF; font-weight: bold;">as</span> Contact<span style="color: #008000;">;</span> 
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>otherContact <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Surname</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CompareTo</span><span style="color: #008000;">&#40;</span>otherContact<span style="color: #008000;">.</span><span style="color: #0000FF;">Surname</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">else</span>
           <span style="color: #0600FF; font-weight: bold;">throw</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArgumentException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Object is not a Contact&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>In order to sort a collection of Contacts, we can simply call the Sort method as follows:</p>

<div class="wp_codebox"><table><tr id="p4769"><td class="code" id="p476code9"><pre class="csharp" style="font-family:monospace;">ArrayList list <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArrayList<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// add some Contacts</span>
list<span style="color: #008000;">.</span><span style="color: #0000FF;">Sort</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>That&#8217;s all well and good, but we will always sort by Contact.Surname. The collection Sort method will automatically use the IComparable CompareTo method defined by each Contact element. If we want to sort by a different property, say PhoneNo, we must use an IComparer.</p>

<div class="wp_codebox"><table><tr id="p47610"><td class="code" id="p476code10"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ContactPhoneNoComparer <span style="color: #008000;">:</span> IComparer
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Compare<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> left, <span style="color: #6666cc; font-weight: bold;">object</span> right<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      Contact first <span style="color: #008000;">=</span> left <span style="color: #0600FF; font-weight: bold;">as</span> Contact<span style="color: #008000;">;</span>
      Contact second <span style="color: #008000;">=</span> right <span style="color: #0600FF; font-weight: bold;">as</span> Contact<span style="color: #008000;">;</span>
      <span style="color: #008080; font-style: italic;">// null checking omitted for brevity</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> first<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CompareTo</span><span style="color: #008000;">&#40;</span>second<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>To sort the Contact collection by PhoneNo we can now do this:</p>

<div class="wp_codebox"><table><tr id="p47611"><td class="code" id="p476code11"><pre class="csharp" style="font-family:monospace;">ArrayList contacts <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArrayList<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// add some Contacts</span>
contacts<span style="color: #008000;">.</span><span style="color: #0000FF;">Sort</span><span style="color: #008000;">&#40;</span><a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ContactPhoneNoComparer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>At least we can centralise our comparison logic in comparer classes, but this .NET 1.1 way of doing things is a bit ugly. Since we are forced to use object, the compiler can&#8217;t do any type checking to save us from our own stupidity. We end up having to write boiler plate code to check our casts. These comparer classes are also a little verbose, especially if we need a lot of them. </p>
<p>What follows is shameless plagarism: when I read chapter 1 of <a href="http://csharpindepth.com/">C# in Depth</a> I realised that it contained what would have been a good answer to my interview question. This is a diversion from the framework foundation, but a worthy one.</p>
<p><strong>IComparer&lt;T&gt;</strong></p>
<p>The casting, which is really the most significant limitation, can be removed by using IComparer&lt;T&gt;. Note that this is now much shorter and more readable.</p>

<div class="wp_codebox"><table><tr id="p47612"><td class="code" id="p476code12"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ContactPhoneNoComparer <span style="color: #008000;">:</span> IComparer<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Compare<span style="color: #008000;">&#40;</span>Contact left, Contact right<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> left<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CompareTo</span><span style="color: #008000;">&#40;</span>right<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Using a lambda expression</strong></p>
<p>Using a lambda expression we can eliminate the IComparer entirely.</p>

<div class="wp_codebox"><table><tr id="p47613"><td class="code" id="p476code13"><pre class="csharp" style="font-family:monospace;">List<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span> contacts <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> List<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// add some Contacts</span>
contacts<span style="color: #008000;">.</span><span style="color: #0000FF;">Sort</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>l, r<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> l<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CompareTo</span><span style="color: #008000;">&#40;</span>r<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><strong>Using the OrderBy extension method</strong></p>
<p>Finally, using an extension method, we can do something even more readable. This time, the original order of the list is preserved, and we get a new contact list in the specified order.</p>

<div class="wp_codebox"><table><tr id="p47614"><td class="code" id="p476code14"><pre class="csharp" style="font-family:monospace;">List<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span> contacts <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> List<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// add some Contacts</span>
List<span style="color: #008000;">&lt;</span>Contact<span style="color: #008000;">&gt;</span> sortedContacts <span style="color: #008000;">=</span> contacts<span style="color: #008000;">.</span><span style="color: #0000FF;">OrderBy</span><span style="color: #008000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c<span style="color: #008000;">.</span><span style="color: #0000FF;">PhoneNo</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/09/sorting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Iteration</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/09/iteration/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/09/iteration/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 21:17:14 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[foreach]]></category>
		<category><![CDATA[ienumerable]]></category>
		<category><![CDATA[indexing]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=473</guid>
		<description><![CDATA[Iteration in .NET can be acomplished in two ways: indexing and using the IEnumerable interface. Indexing is an elementary programming concept covered elsewhere. IEnumerable &#038; IEnumerator The IEnumerable interface would perhaps have been better named IForwardIteratable, since it defines a scheme for forward only iteration. IEnumerable specifies a single method, GetEnumerator, which returns an IEnumerator, [...]]]></description>
			<content:encoded><![CDATA[<p>Iteration in .NET can be acomplished in two ways: <a href="http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx">indexing</a> and using the <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx">IEnumerable</a> interface. Indexing is an elementary programming concept covered <a href="http://msdn.microsoft.com/en-us/library/2549tw02.aspx">elsewhere</a>.</p>
<p><strong>IEnumerable &#038; IEnumerator</strong></p>
<p>The IEnumerable interface would perhaps have been better named IForwardIteratable, since it defines a scheme for forward only iteration. IEnumerable specifies a single method, GetEnumerator, which returns an IEnumerator, the actual forward iterator. IEnumerator specifies three members:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.current.aspx">Current</a> property: the collection element to which the iterator is pointing.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext.aspx">MoveNext</a> method: moves the iterator to the next element in the collection. Returns false when the iterator has passed the final element.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx">Reset</a> method: set the iterator to the initial state, where calling MoveNext results in the iterator pointing at the first element.</li>
</ul>
<p>You may then traverse a collection as follows:</p>

<div class="wp_codebox"><table><tr id="p47317"><td class="code" id="p473code17"><pre class="csharp" style="font-family:monospace;">IEnumerator enumerator <span style="color: #008000;">=</span> collection<span style="color: #008000;">.</span><span style="color: #0000FF;">GetEnumerator</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>enumerator<span style="color: #008000;">.</span><span style="color: #0000FF;">MoveNext</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>enumerator<span style="color: #008000;">.</span><span style="color: #0000FF;">Current</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>foreach</strong></p>
<p>The code snippet above might seem a little cumbersome. To improve matters both VB and C# provide the foreach language level construct. Using foreach the example above becomes simply:</p>

<div class="wp_codebox"><table><tr id="p47318"><td class="code" id="p473code18"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> element <span style="color: #0600FF; font-weight: bold;">in</span> collection<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>element<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Notice that this scheme is based on object rather than the derived type in the collection. So, if you don&#8217;t use generic collections, there <em>might</em> be an implicit cast from IEnumerator.Current to the target type.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/09/iteration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collections</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/09/collections/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/09/collections/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 20:32:17 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[boxing]]></category>
		<category><![CDATA[Collections]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=451</guid>
		<description><![CDATA[The overarching design of System.Collections is obscured by the poorly conceived nomenclature (others concur). Concrete collections in .NET are based on these key interfaces: IEnumerable simply provides a method to return an IEnumerator. IEnumerator provides the mechanism for forward only iteration. ICollection extends IEnumerable adding some basic machinery for thread safe access and a Count [...]]]></description>
			<content:encoded><![CDATA[<p>The overarching design of <a href="http://msdn.microsoft.com/en-us/library/system.collections.aspx">System.Collections</a> is obscured by the poorly conceived nomenclature (<a href="http://aspnetresources.com/blog/dotnet_collection_madness.aspx">others</a> concur). Concrete collections in .NET are based on these key interfaces:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx">IEnumerable</a> simply provides a method to return an <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx">IEnumerator</a>. IEnumerator provides the mechanism for forward only iteration.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.aspx">ICollection</a> extends IEnumerable adding some basic machinery for thread safe access and a Count property. Note that ICollection does not provide any way of adding/removing elements.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx">IList</a> extends ICollection to support indexing and the facility to add and remove elements. ILists can be fixed size and/or read only.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.idictionary.aspx">IDictionary</a> extends ICollection to support  key value pairs. Values may be added, retrieved and removed by key. Both the keys and the values can be retreived as ICollections. IDictionarys can be fixed size and/or read only.</li>
</ul>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a> : <a href="http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx">IList</a></strong></p>
<p>ArrayList provides an IList interface over an array which is dynamically resized as you insert elements. Iterating over an ArrayList returns items in the order they were inserted (unless it has been sorted).</p>
<p>The following snippet demonstrates adding, inserting and removing elements and ranges of elements.</p>

<div class="wp_codebox"><table><tr id="p45120"><td class="code" id="p451code20"><pre class="csharp" style="font-family:monospace;">ArrayList al <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArrayList<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
al<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;this&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Add range requires an ICollection arg</span>
<span style="color: #6666cc; font-weight: bold;">string</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> strs <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;is&quot;</span>, <span style="color: #666666;">&quot;a&quot;</span>, <span style="color: #666666;">&quot;list&quot;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
al<span style="color: #008000;">.</span><span style="color: #0000FF;">AddRange</span><span style="color: #008000;">&#40;</span>strs<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
al<span style="color: #008000;">.</span><span style="color: #0000FF;">Insert</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, <span style="color: #666666;">&quot;hello&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> more <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;non&quot;</span>, <span style="color: #666666;">&quot;sense&quot;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
al<span style="color: #008000;">.</span><span style="color: #0000FF;">InsertRange</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">1</span>, more<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
al<span style="color: #008000;">.</span><span style="color: #0000FF;">RemoveAt</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
al<span style="color: #008000;">.</span><span style="color: #0000FF;">RemoveRange</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Note that runtime performance is similar to what you might expect if manipulating a raw array. For example, in the worst case, InsertRange is an O(<em>m</em> + <em>n</em>) operation, where <em>n</em> is the number of elements to be added and <em>m</em> is the number of elements in the ArrayList.</p>
<p><strong>Casting and boxing</strong></p>
<p>System.Collections classes come from a time before .NET generics. As a consequence, collection elements are <a href="http://msdn.microsoft.com/en-us/library/system.object.aspx">objects</a> &#8211; everything is cast to/from object as it is stored/retrieved. Value types also get boxed/uboxed. This is all additional overhead.</p>
<p>Contary to what it says in the Framework Foundation book, generics are *sometimes* faster because they avoid this casting and boxing (depending on your use case). Rico Mariani has an interesting <a href="http://blogs.msdn.com/ricom/archive/2005/08/25/performance-quiz-7-generics-improvements-and-costs.aspx">performance comparison</a> (the real killer is the repeated allocation of the ArrayList Enumerator).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/09/collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Encoding and Decoding</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/09/encoding-and-decoding/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/09/encoding-and-decoding/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 17:52:34 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[Decoding]]></category>
		<category><![CDATA[Encoding]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=294</guid>
		<description><![CDATA[Encoding is the process of transforming a sequence of characters into a sequence of bytes, decoding is the reversal of this process. It is important to employ the correct encoding format, and particular attention should be paid when performing low level string operations or working with programs designed for regions which use non latin alphabets. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx">Encoding</a> is the process of transforming a sequence of characters into a sequence of bytes, decoding is the reversal of this process. It is important to employ the correct encoding format, and particular attention should be paid when performing low level string operations or working with programs designed for regions which use non <a href="http://en.wikipedia.org/wiki/Basic_modern_Latin_alphabet">latin alphabets</a>.</p>
<p><strong>ASCII, ISO and Unicode</strong></p>
<p>The venerable <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> encoding standard is the basis for modern character encoding. ASCII encodes non printable control characters, as well as a modern latin alphabet, digits, punctuation marks, and a few miscellaneous symbols. These values are encoded in 7-bits (0-127). ASCII does not standardise use of values 128 to 255 in 8-bits; different regions invented their own standards and this makes it difficult to exchange text encoded using potentially different standards across regions.</p>
<p>ANSI went some way toward solving this by defining standardised code pages consisting of both the standard ASCII values (0-127) and language specific values (128-255). For example, <a href="http://en.wikipedia.org/wiki/ISO/IEC_8859-1">ISO 8859-1</a> is intended for western european languages. Clearly, ISO 8859 encodings are still not truly interoperable, but at least you know which characters are represented between 128-255.</p>
<p><a href="http://en.wikipedia.org/wiki/Unicode">Unicode</a> was introduced almost twenty years ago to provide a world text encoding scheme, capable of encoding the characters used in every living language. Although initially restricted to 16-bits, there are now multiple Unicode encoding schemes.</p>
<p><strong>System.Text Encodings</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.text.utf32encoding.aspx">UTF32Encoding</a> is a UTF-32 encoding representing each code point as a 32-bit integer.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx">UnicodeEncoding</a> is a UTF-16 encoding representing each code point as a sequence of one to two 16-bit integers.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.aspx">UTF8Encoding</a> is a UTF-8 encoding representing each code point as a sequence of one to four bytes.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.text.utf7encoding.aspx">UTF7Encoding</a> is a UTF-7 encoding representing Unicode characters as sequences of 7-bit ASCII characters.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.text.asciiencoding.aspx">ASCIIEncoding</a> corresponds to the Windows code page 20127. ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F.</li>
<li>ANSI/ISO encodings can be accessed via the <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.getencoding.aspx">Encoding.GetEncoding</a> method. <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx">This</a> page gives a list of the supported encodings.</li>
</ul>
<p>I was struck by the inconsistent naming of these classes, and that they don&#8217;t follow Microsoft&#8217;s naming conventions for <a href="http://msdn.microsoft.com/en-us/library/ms229043.aspx">capitalisation</a>.</p>
<p><strong>A simple example</strong></p>
<p>Using <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.getencoding.aspx">Encoding.GetEncoding</a> we can retrieve a Western European codepage, then get some encoded bytes using the GetBytes method. This is only slightly more typing than using one of the standard encoding classes described above.</p>

<div class="wp_codebox"><table><tr id="p29424"><td class="code" id="p294code24"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> westernEuroBytes <span style="color: #008000;">=</span> Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">GetEncoding</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Windows-1252&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetBytes</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;foo bar&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> utf16Bytes <span style="color: #008000;">=</span> Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">Unicode</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetBytes</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;foo bar&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><strong>Enumerating supported code pages</strong></p>
<p>You can enumerate the available encodings as follows, this essentially reproduces the table found <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx">here</a>.</p>

<div class="wp_codebox"><table><tr id="p29425"><td class="code" id="p294code25"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>EncodingInfo ei <span style="color: #0600FF; font-weight: bold;">in</span> Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">GetEncodings</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}, {1}, {2}&quot;</span>, ei<span style="color: #008000;">.</span><span style="color: #0000FF;">CodePage</span>, ei<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span>, ei<span style="color: #008000;">.</span><span style="color: #0000FF;">DisplayName</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Encoding &#038; File I/O</strong></p>
<p>If you use an encoding other than UTF7, you must explicitly declare it when reading from the file, as follows.</p>

<div class="wp_codebox"><table><tr id="p29426"><td class="code" id="p294code26"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>StreamWriter sw <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> StreamWriter<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;filename.txt&quot;</span>, <span style="color: #0600FF; font-weight: bold;">false</span>, Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">Unicode</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    sw<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;foo bar&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>StreamReader sw <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> StreamReader<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;filename.txt&quot;</span>, Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">Unicode</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> line <span style="color: #008000;">=</span> sw<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>If you encode the file using ASCII, you can decode it using ASCII, UTF-7 and UTF-8 encodings. UTF-16 and UTF-32 use larger bytes, and are therefore incompatible.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/09/encoding-and-decoding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regular Expressions</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/08/regular-expressions/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/08/regular-expressions/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 18:17:18 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=292</guid>
		<description><![CDATA[Regular Expressions are used to match patterns in strings. These patterns may be particular character sequences, character classes (e.g. white space, digits, upper case etc) or combinations thereof. Patterns may be combined to form more complex patterns using repetition and alternation operators. For a more detailed treatment, please refer to this site, which is worth [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Regular_expression">Regular Expressions</a> are used to match patterns in strings. These patterns may be particular character sequences, character classes (e.g. white space, digits, upper case etc) or combinations thereof. Patterns may be combined to form more complex patterns using repetition and alternation operators. </p>
<p>For a more detailed treatment, please refer to <a href="http://www.regular-expressions.info/">this</a> site, which is worth visiting just to see the photograph of the author. If that&#8217;s too long winded, try the <a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/">cheat sheet</a> instead.</p>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx">Regex</a>: A Simple Example</strong></p>
<p>Whilst the concept is simple, RegEx syntax is not.  RegEx&#8217;s can be hard to read. This expression matches a UK postcode:</p>

<div class="wp_codebox"><table><tr id="p29232"><td class="code" id="p292code32"><pre class="xx" style="font-family:monospace;">^[A-Za-z]{1,2}[\d]{1,2}([A-Za-z])?\s?[\d][A-Za-z]{2}$</pre></td></tr></table></div>

<p>This example includes several key bits of RegEx syntax. The ^ and $ characters are anchors, and specify the beginning and end. Square brackets denote a character set to match, [A-Za-z] matches upper and lower case characters in the range A-Z. Curly braces denote the number of matches, so [A]{1,2} will match the character A once or twice. The ? matches the preceeding expression zero or once, so \s? matches a white space character zero or once.</p>
<p>In the context of .NET, the <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx">Regex</a> class provides static methods to test a string for a match. Here is a simple but useless example:</p>

<div class="wp_codebox"><table><tr id="p29233"><td class="code" id="p292code33"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>RegEx<span style="color: #008000;">.</span><span style="color: #0000FF;">IsMatch</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;pattern&quot;</span>, <span style="color: #666666;">@&quot;^[aenprt]{1,7}$&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">// do something...</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Options</strong></p>
<p>RegEx methods and constructors, where appropriate, provide an override where <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx">RegexOptions</a> may be specified (e.g. compiled, case sensitive etc.). Options may be combined using a bitwise OR. You can also <a href="http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx">specify options inline</a> within the regex pattern, by enclosing characters which map to regex options within brackets. There are two forms:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bs2twtah.aspx">Grouping construct</a> (?imnsx-imnsx:)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/x044wc7s.aspx">Miscelleneous construct</a> (?imnsx-imnsx)</li>
</ul>
<p>Prefixing a set of options with the minus sign turns them off. All the options are turned off by default. Compiled and RightToLeft may only be applied to an expression as a whole.</p>
<p><strong>Grouping &#038; Backreferences</strong></p>
<p>Round brackets specify a group, and when referring back to a group it is possible to apply alternation and repitition operators. A simple example might be to search for repeating sequences of numbers preceeded by a space:</p>

<div class="wp_codebox"><table><tr id="p29234"><td class="code" id="p292code34"><pre class="xx" style="font-family:monospace;">(?&lt;groupname&gt;\s\d)\k&lt;groupname&gt;</pre></td></tr></table></div>

<p>The (?<name>pattern) construct is used to denote the group, then \k<name> is used to refer back to the group. If you don&#8217;t specify a name within angle brackets, you can refer to groups by number using \l<em>n</em>, where <em>n</em> is the group number.</p>
<p><strong>Extracting matches</strong></p>
<p>Using the static <a href="http://msdn.microsoft.com/en-us/library/0z2heewz.aspx">Regex.Match</a> method you may extract matches from an input string. The  sub pattern you wish to extract should be enclosed in parentheses.</p>

<div class="wp_codebox"><table><tr id="p29235"><td class="code" id="p292code35"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> input <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Exception: error message&quot;</span><span style="color: #008000;">;</span>
Match m <span style="color: #008000;">=</span> Regex<span style="color: #008000;">.</span><span style="color: #0000FF;">Match</span><span style="color: #008000;">&#40;</span>input, <span style="color: #666666;">&quot;Exception: (.*$)&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> match1 <span style="color: #008000;">=</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">Groups</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
&nbsp;
CaptureCollection captures <span style="color: #008000;">=</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">Groups</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Captures</span><span style="color: #008000;">;</span>
Capture c <span style="color: #008000;">=</span> captures<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;group '{0}', capture '{1}', index {2}&quot;</span>, match1, c<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span>, c<span style="color: #008000;">.</span><span style="color: #0000FF;">Index</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// prints: group 'error message', capture 'error message', index 11</span></pre></td></tr></table></div>

<p>If there is a match, the Match.Success property = true. The Match.Groups array contains the matches, indexed starting at 1. If you name the groups (using angle brackets as described above), you can also index by name. Groups comprise of capture collections, and each capture contains the match along with index and length properties.</p>
<p><strong>Replacing matches</strong></p>
<p>Using the static <a href="http://msdn.microsoft.com/en-us/library/e7f5w83z.aspx">Regex.Replace</a> method you may replace matches within the input string. This simple example shows how to use named backreferences within the replacement pattern.</p>

<div class="wp_codebox"><table><tr id="p29236"><td class="code" id="p292code36"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> output <span style="color: #008000;">=</span> Regex<span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;alex peck&quot;</span>, <span style="color: #666666;">@&quot;(?&lt;forename&gt;\S+) (?&lt;surname&gt;\S+)&quot;</span>, <span style="color: #666666;">&quot;${surname}, ${forename}&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// output = &quot;peck, alex&quot;</span></pre></td></tr></table></div>

<p>The replacement expression ${surname} inserts the match captured by the group (?<surname>). We could also use the expression $<em>n</em>, where <em>n</em> is an integer, to insert groups by number.</p>
<p><strong>Online resources</strong></p>
<ul>
<li><a href="http://regexlib.com/">regexlib</a> &#8211; Regular Expression Library</li>
<li><a href="http://regexpal.com/">regexpal</a> &#8211; Test regular expressions in a web page (based on java)</li>
<li>Regulator and Regulazy are available <a href="http://osherove.com/tools">here</a></li>
<li><a href="http://osteele.com/tools/reanimator/">reanimator</a> &#8211; animate your regex as an automaton</li>
<li>.NET <a href="http://msdn.microsoft.com/en-us/library/az24scfc%28VS.71%29.aspx">MSDN</a> reference</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/08/regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>StringBuilder</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/07/stringbuilder/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/07/stringbuilder/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 18:17:42 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[StringBuilder]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=290</guid>
		<description><![CDATA[Since strings in .NET are immutable, StringBuilder is used when you need to work with mutable string data &#8211; i.e. appending, removing, replacing, or inserting characters. MSDN states that most of the methods that modify an instance of this class return a reference to that same instance. Since a reference to the instance is returned, [...]]]></description>
			<content:encoded><![CDATA[<p>Since strings in .NET are immutable, <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx">StringBuilder</a> is used when you need to work with mutable string data &#8211; i.e. appending, removing, replacing, or inserting characters.</p>
<p>MSDN states that <em>most of the methods that modify an instance of this class return a reference to that same instance. Since a reference to the instance is returned, you can call a method or property on the reference. This can be convenient if you want to write a single statement that chains successive operations one after another</em>.</p>
<p>Performance consideration: StringBuilder is only really advantageous when working with larger string operations, like concatenating tens of strings in a loop. This is due to the overhead of creating a StringBuilder vs a string &#8211; StringBuilder is obviously more complex. Rico Mariani provides similar <a href="http://blogs.msdn.com/ricom/archive/2003/12/15/43628.aspx">advice</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/07/stringbuilder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Isolated Storage</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/07/isolated-storage/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/07/isolated-storage/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 19:08:04 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[Isolated Storage]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=254</guid>
		<description><![CDATA[Isolated storage is provided so that applications running with least privilege are able to store data. .NET provides isolated storage equivalents for both File and FileStream. IsolatedStorageFile IsolatedStorageFile provides functionality to create files and folders in isolated storage. The first step is to create a store, which can be scoped as either Assembly/Machine or Assembly/User. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx"><br />
Isolated storage</a> is provided so that applications running with least privilege are able to store data. .NET provides isolated storage equivalents for both File and FileStream.</p>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.aspx">IsolatedStorageFile</a> </strong></p>
<p>IsolatedStorageFile provides functionality to create files and folders in isolated storage. The first step is to create a store, which can be scoped as either Assembly/Machine or Assembly/User. If you use machine scope, then all users can access the data. So, user specific data should go in user scope, application data in machine scope.</p>

<div class="wp_codebox"><table><tr id="p25441"><td class="code" id="p254code41"><pre class="csharp" style="font-family:monospace;">IsolatedStorageFile machineStore <span style="color: #008000;">=</span> IsolatedStorageFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GetMachineStoreForAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
IsolatedStorageFile userStore <span style="color: #008000;">=</span> IsolatedStorageFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GetUserStoreForAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Click once applications can also access an <a href="http://blogs.msdn.com/shawnfa/archive/2006/01/18/514407.aspx">application scope</a>.</p>
<p>Once you have created a store you can use instance methods to manipulate files and directories. Instance properties allow you to evaluate current and maximum size, scope, and the identities (Application, Assembly, Domain) used for scoping.</p>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefilestream.aspx">IsolatedStorageFileStream</a></strong></p>
<p>The IsolatedStorageFileStream class derives from FileStream, see <a href="http://blog.hypercomplex.co.uk/index.php/2009/07/net-streams/">.NET streams</a> for more details. Here is an example of writing within a directory:</p>

<div class="wp_codebox"><table><tr id="p25442"><td class="code" id="p254code42"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>IsolatedStorageFile userStore <span style="color: #008000;">=</span> IsolatedStorageFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GetUserStoreForAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    userStore<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateDirectory</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;testDir&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>IsolatedStorageFileStream userStream <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> IsolatedStorageFileStream<span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;testDir\user.set&quot;</span>, FileMode<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenOrCreate</span>, userStore<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>StreamWriter userWriter <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> StreamWriter<span style="color: #008000;">&#40;</span>userStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            userWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;user data&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>It&#8217;s slightly annoying that there is no directory exists method, so testing this before creating a directory involves calling GetDirectoryNames then iterating over the string array it returns &#8211; I didn&#8217;t show this for brevity. Here is how to read it back:</p>

<div class="wp_codebox"><table><tr id="p25443"><td class="code" id="p254code43"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>IsolatedStorageFile userStore <span style="color: #008000;">=</span> IsolatedStorageFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GetUserStoreForAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>IsolatedStorageFileStream userStream <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> IsolatedStorageFileStream<span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;testDir\user.set&quot;</span>, FileMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span>, userStore<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        StreamReader userReader <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> StreamReader<span style="color: #008000;">&#40;</span>userStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span> data <span style="color: #008000;">=</span> userReader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Permissions</strong></p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.isolatedstoragepermission.aspx">IsolatedStoragePermission</a> class defines access to isolated storage capabilities. If you use isolated storage it is best practice to add an IsolatedStoragePermission attribute.</p>

<div class="wp_codebox"><table><tr id="p25444"><td class="code" id="p254code44"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>IsolatedStorageFilePermission<span style="color: #008000;">&#40;</span>SecurityAction<span style="color: #008000;">.</span><span style="color: #0000FF;">Demand</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span> <span style="color: #008080; font-style: italic;">/* ... */</span> <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/07/isolated-storage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FileSystemWatcher</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/07/filesystemwatcher/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/07/filesystemwatcher/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 23:14:49 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[FileSystemWatcher]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=209</guid>
		<description><![CDATA[The FileSystemWatcher class provides a mechanism for raising events based on changes to the file system (files or directories). The Filter property allows you to specify which file(s) you are interested in watching. The NotifyFilter allows you to specify which events to watch for (created/modified/deleted etc.). You can also specify whether or not to IncludeSubdirectories. [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx">FileSystemWatcher</a> class provides a mechanism for raising events based on changes to the file system (files or directories).</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx">Filter</a> property allows you to specify which file(s) you are interested in watching. The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.notifyfilter.aspx">NotifyFilter</a> allows you to specify which events to watch for (created/modified/deleted etc.). You can also specify whether or not to <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.includesubdirectories.aspx">IncludeSubdirectories</a>. Using these properties correctly ensures that a manageable amount of file system events are raised (see below).</p>
<p>FileSystemWatcher events use three delegate types:</p>
<ul>
<li>Changed, Created, Deleted events use FileSystemEventHandler</li>
<li>Renamed events use a RenamedEventHandler </li>
<li>Error events use a ErrorEventHandler</li>
</ul>
<p>You should minimise the work performed in these event handlers, otherwise you can impact the number of events you may handle.</p>
<p>There is also a synchronous WaitForChanged method which returns a structure containing changes.</p>
<p><strong>Caveats</strong></p>
<p>I would advise setting the error handler first, otherwise you can get silent failures when setting other properties.</p>
<p>Generally, it is not advisable to use FileSystemWatcher on network drives. If/when a network outage occurs the watcher ceases to function, a simple workaround is given <a href="http://www.codeguru.com/csharp/.net/net_general/eventsanddelegates/article.php/c9113">here</a>.</p>
<p>The underlying Win 32 ReadDirectoryChangesW function will fail with ERROR_INVALID_PARAMETER if the buffer length is greater than 64 KB and the application is monitoring a directory over a network. This is due to a packet size limitation with the underlying file sharing protocols.</p>
<p>Furthermore, there is no guarantee that you will recieve notification of every change under heavy load scenarios. This is compounded for network shares, since you have a smaller buffer size limitation. See <a href="http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/">this</a> page for a detailed explanation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/07/filesystemwatcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET Readers and Writers</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/07/net-readers-and-writers/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/07/net-readers-and-writers/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 14:50:13 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=213</guid>
		<description><![CDATA[TextReader and TextWriter are abstract base classes which define methods to read and write a sequential series of characters. Using TextReader/Writer provides a handy seam for unit testing, since we can substitute text read/written to a stream with data that comes simply from a string. Classes derived from both these base classes implement IDisposable. StreamReader [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/system.io.textreader.aspx">TextReader</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.textwriter.aspx">TextWriter</a> are abstract base classes which define methods to read and write a sequential series of characters. Using TextReader/Writer provides a handy seam for unit testing, since we can substitute text read/written to a stream with data that comes simply from a string. Classes derived from both these base classes implement <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable</a>.</p>
<p><strong>StreamReader &#038; StreamWriter</strong></p>
<p>In the previous post, strings were read and written to streams as byte arrays based on an encoding. <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx">StreamReader</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx">StreamWriter</a> allow strings to be read and written to steams more conveniently. Of course, they are derived from TextReader/Writer.</p>
<p><strong>StringReader &#038; StringWriter</strong><br />
<a href="http://msdn.microsoft.com/en-us/library/system.io.stringreader.aspx">StringReader</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx">StringWriter</a> provide similar functionality for reading and writing to strings. The writer is based on an underlying <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx">StringBuilder</a>.</p>
<p><strong>BinaryReader &#038; BinaryWriter</strong></p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx">BinaryReader</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx">BinaryWriter</a> classes are closely related and read/write binary data to streams. They do not inherit from the text abstract bases (since they are not text based). They also implement <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/07/net-readers-and-writers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET Streams</title>
		<link>http://blog.hypercomplex.co.uk/index.php/2009/07/net-streams/</link>
		<comments>http://blog.hypercomplex.co.uk/index.php/2009/07/net-streams/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 21:40:56 +0000</pubDate>
		<dc:creator>Alex Peck</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Application Development Foundation]]></category>
		<category><![CDATA[stream]]></category>

		<guid isPermaLink="false">http://blog.hypercomplex.co.uk/?p=211</guid>
		<description><![CDATA[The Stream base class is an abstraction of a sequence of bytes. A stream may be sequential or random access. .NET defines several derived stream classes, not all of which reside in System.IO. Stream implements IDisposable. Stream overview Stream presents properties to determine whether a stream CanRead, CanWrite, CanSeek or CanTimeout. Streams that support seeking [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.aspx">Stream</a> base class is an abstraction of a sequence of bytes. A stream may be sequential or random access. .NET defines several derived stream classes, not all of which reside in System.IO. Stream implements <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable</a>.</p>
<p><strong>Stream overview</strong></p>
<p>Stream presents properties to determine whether a stream CanRead, CanWrite, CanSeek or CanTimeout. Streams that support seeking implement the Position and Length properties.</p>
<p>Stream presents virtual methods to sequentially read and write (Read, ReadByte, Write, WriteByte), as well as Flush, Seek, SetLength and Close.</p>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx">FileStream</a></strong></p>
<p>This example illustrates how to write and read to a file, using the static <a href="http://msdn.microsoft.com/en-us/library/system.io.file.aspx">File</a> class to create the required FileStreams.</p>

<div class="wp_codebox"><table><tr id="p21150"><td class="code" id="p211code50"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">string</span> path <span style="color: #008000;">=</span> <span style="color: #666666;">@&quot;C:\file.txt&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>FileStream fs <span style="color: #008000;">=</span> File<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span>path<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> info <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> UTF8Encoding<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetBytes</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;some text to write&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    fs<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>info, <span style="color: #FF0000;">0</span>, info<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>FileStream fs <span style="color: #008000;">=</span> File<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span>path, FileMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span>, FileAccess<span style="color: #008000;">.</span><span style="color: #0000FF;">Read</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> b <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1024</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
    UTF8Encoding encoding <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> UTF8Encoding<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>fs<span style="color: #008000;">.</span><span style="color: #0000FF;">Read</span><span style="color: #008000;">&#40;</span>b, <span style="color: #FF0000;">0</span>, b<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> 
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">GetString</span><span style="color: #008000;">&#40;</span>b<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx">MemoryStream</a></strong></p>
<p>You could repeat the above example, but substitute the FileStream for a MemoryStream.</p>

<div class="wp_codebox"><table><tr id="p21151"><td class="code" id="p211code51"><pre class="csharp" style="font-family:monospace;">MemoryStream ms <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> MemoryStream<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>MemoryStream also provides the facility to write to another stream, like so:</p>

<div class="wp_codebox"><table><tr id="p21152"><td class="code" id="p211code52"><pre class="csharp" style="font-family:monospace;">MemoryStream ms <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> MemoryStream<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// write some data to ms</span>
FileStream fs <span style="color: #008000;">=</span> File<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;C:\mem.txt&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ms<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteTo</span><span style="color: #008000;">&#40;</span>fs<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
fs<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ms<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx">BufferedStream</a></strong></p>
<p>In order to improve performance, BufferedStream adds a buffering layer to read and write operations on another stream. For example:</p>

<div class="wp_codebox"><table><tr id="p21153"><td class="code" id="p211code53"><pre class="csharp" style="font-family:monospace;">FileStream fs <span style="color: #008000;">=</span> File<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;C:\buffered.txt&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
BufferedStream bs <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> BufferedStream<span style="color: #008000;">&#40;</span>fs<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// write data to bs like any other stream</span></pre></td></tr></table></div>

<p><strong>Compressed streams</strong></p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.aspx">System.IO.Compression</a> namespace provides the <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx">GZipStream</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx">DeflateStream</a> classes. Both use the same compression algorithm (which does not depend on any patents). GZipStream writes data with headers that allow the data to be decompressed with GZip, and therefore has a slightly larger footprint.</p>
<p>Compressed streams may be used in a similar fashion to buffering:</p>

<div class="wp_codebox"><table><tr id="p21154"><td class="code" id="p211code54"><pre class="csharp" style="font-family:monospace;">FileStream destination <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> FileStream<span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;C:\compressed.txt&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// when writing to gzipStream, we compress data then write it to the destination stream</span>
GZipStream gzipStream <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> GZipStream<span style="color: #008000;">&#40;</span>destination, CompressionMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Compress</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> buffer <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">256</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// put some data in the buffer</span>
gzipStream<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>buffer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Decompression is essentially the same, except you perform reads instead of writes.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hypercomplex.co.uk/index.php/2009/07/net-streams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
