<?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>Martijn's C# Programming Blog &#187; Algorithms</title>
	<atom:link href="http://www.dijksterhuis.org/category/algorithms/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>C# Autosuggestion Textbox</title>
		<link>http://www.dijksterhuis.org/autosuggestion-textbox/</link>
		<comments>http://www.dijksterhuis.org/autosuggestion-textbox/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 21:24:56 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[textbox]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=938</guid>
		<description><![CDATA[A few days ago I needed a textbox that automatically suggests common input options to the user. In my situation, names of companies. Because of screen space constraints I am unable to use a ComboBox (which already has this functionality). 
The idea is that if the user enters one or more characters that the Textbox [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>A few days ago I needed a textbox that automatically suggests common input options to the user. In my situation, names of companies. Because of screen space constraints I am unable to use a ComboBox (which already has this functionality). </p>
<p>The idea is that if the user enters one or more characters that the Textbox will search its list of suggestions. In this test implementation this is done through a simple <em>List<></em>. Ultimately my list will contain many thousands of items and I will need to replace the <em>List<></em> with a more efficient search algorithm. </p>
<p>In the below example code typing a single &#8220;W&#8221; will expand to &#8220;Waterland&#8221;, if you continue typing beyond the final &#8220;d&#8221; it will suggest &#8220;Waterland Investments&#8221;. Type a &#8220;T&#8221; and it will branch to &#8220;Waterland Telecommunication Systems&#8221;. </p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Dijksterhuis.org
{
    class AutoSuggestControl : TextBox
    {
        List&lt;string&gt; Suggestions;
        int PreviousLength; 

        // V1.0 We are using a simple sorted list for the suggestions
        public AutoSuggestControl() : base()
        {
            Suggestions = new List&lt;string&gt;();

            // We keep track of the previous length of the string
            // If the user tries to delete characters we do not interfere
            PreviousLength = 0; 

            // Very basic list, too slow to be suitable for systems with many entries
            Suggestions.Add(&quot;Waterland&quot;);
            Suggestions.Add(&quot;Waterland Investments&quot;);
            Suggestions.Add(&quot;Waterland Telecommuncation Systems&quot;);
            Suggestions.Sort();
        }

        /// &lt;summary&gt;
        /// Search through the collection of suggestions for a match
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Input&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        private string FindSuggestion(string Input)
        {
            if (Input != &quot;&quot;)
            foreach (string Suggestion in Suggestions)
            {
                if (Suggestion.StartsWith(Input))
                    return Suggestion;
            }
            return null;
        }

        /// &lt;summary&gt;
        /// We only interfere after receiving the OnTextChanged event.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;e&quot;&gt;&lt;/param&gt;
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);

            // We don&#039;t do anything if the user is trying to shorten the sentence
            int CursorPosition = SelectionStart;
            if (Text.Length &gt; PreviousLength &amp;&amp; CursorPosition &gt;= 0)
            {
                string Suggestion = FindSuggestion(Text.Substring(0, CursorPosition));
                if (Suggestion != null)
                {
                    // Set the contents of the textbox to the suggestion
                    Text = Suggestion;
                    // Setting text puts the cursor at the beginning of the textbox, so we need to reposition it
                    Select(CursorPosition, 0);
                }
            }
            PreviousLength = Text.Length;
        }

    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/autosuggestion-textbox/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Linked lists in C# &#8211; Part II</title>
		<link>http://www.dijksterhuis.org/using-linked-lists-in-c-part-ii/</link>
		<comments>http://www.dijksterhuis.org/using-linked-lists-in-c-part-ii/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 07:32:48 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[linked list]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=415</guid>
		<description><![CDATA[In a previous post I looked at how to build a very simple linked list in C#.. That class had many problems, including that it exposed quite a bit of its inner workings to the outside world. In this post I will introduce a C# generic LinkedList class that implements the Java LinkedList specification and [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>In <a href="http://www.dijksterhuis.org/using-linked-lists-in-c-part-i/">a previous post</a> I looked at how to build a very simple linked list in C#.. That class had many problems, including that it exposed quite a bit of its inner workings to the outside world. In this post I will introduce a C# generic LinkedList class that implements the Java LinkedList specification and behaves accordingly. I used this opportunity to explore how to apply unit testing with NUnit to effectively test the development process.</em></p>
<p><span id="more-415"></span></p>
<p>First of all, C# already has a generic LinkedList implementation, found in the System.Collections class. If you are looking for that class, the MSDN website <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx">provides a solid introduction</a>.</p>
<p>After building a basic link list class in a previous post, I decided to extend it. To avoid cloning the C# System.Collections class completely I used the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html">Java LinkedList specification</a> instead to roll my own. That meant implementing an iterator and methods such as AddFirst, AddLast, Clear, ToArray etc. To be able to support this the internal working of my earlier class had to be reworked substantially. I have included the complete code for reference below.</p>
<p>My main purpose for writing this code was to experiment with using NUnit. NUnit is a testing framework which allows you to create unit tests for your code. As you implement a method you write a small test to ensure that it works correctly. Because you are adding functionality to the class as you write new code the underlying methods might change in unexpected ways. Unit tests help you catch bugs introduced this way.</p>
<p>In earlier posts I commented on how to <a href="http://www.dijksterhuis.org/setting-up-nunit-for-c-unit-testing-with-visual-studio-c-express-2008/">use NUnit if you are coding in Visual Studio C# 2008 Express</a> ; and <a href="http://www.dijksterhuis.org/using-nunit-with-monodevelop/">how to use NUnit if you are building your applications with MonoDevelop</a> so if you are having trouble setting this up please refer to these.</p>
<p><strong>Creating new and interesting bugs</strong></p>
<p>As a late optimization to my LinkedList class I added &#8220;Search Backwards&#8221; logic to the &#8220;Get(n)&#8221; method. </p>
<p>As you can guess, the &#8220;Get(n)&#8221; method returns the n<sup>th</sup> item in the list. To find it the n<sup>th</sup> element we need to step through the list from the start. If we work out that the item is closer the tail of the list we can save some time by stepping backwards through the list instead. Unit testing helped here as I had made a small bit significant error in how I calculated the distance from the tail. Several tests immediately failed as they now received unexpected results.</p>
<p><strong>Creating the Unit Tests</strong></p>
<p>The best place to put your tests is in a separate class file. As can be seen in the code snippet below the first thing we need to do is to include the NUnit.Framework in the code. The first thing to notice about this class is that it has a [TestFixture] attribute – this is how we indicate that the class contains test code. The class has to be public.  As we can run NUnit tests independently of your programs main routine, NUnit will simply load your programs classes and use the [TestFixture] attribute to discover any and all tests classes.</p>
<p>Each method containing a valid test has a [Test] attribute associated with it. Again, NUnit will simply scan the [TestFixture] classes for any method labeled with a [Test] attribute.</p>
<p>In the example below I included a very simple test for the Add() method of my linked list. After adding 2 items to the LinkedList, the total number of items has to be 2. Testing is done through the Assert class, if the Assert test fails, NUnit will flag the test as failed. Some other common Assert methods are: AreEqual(a,b) / AreNotEquels(a,b) / Equals  / IsTrue / IsFalse etc.</p>
<pre class="brush: c#">
using System;
using System.Text;
using NUnit.Framework;

namespace LinkedListJavaStyle
{
    /// &lt;summary&gt;
    /// LinkedList_NUnit is a class implementing a set of unit tests for each of the methods supported by the LinkedList class
    /// &lt;/summary&gt;

    [TestFixture]
    public class LinkedList_NUnit
    {

        [Test]
        public void TestLinkedList_add()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Assert.AreEqual(2, Test.Size());
        }
}
</pre>
<p>The complete LinkedListClass.cs and set of tests (LinkedList_NUnit.cs) are given below: </p>
<p><strong>LinkedList.cs</strong></p>
<pre class="brush: c#">
using System;
using System.Text;
using NUnit.Framework;

namespace LinkedListJavaStyle
{
    /// &lt;summary&gt;
    /// LinkedList_NUnit is a class implementing a set of unit tests for each of the methods supported by the LinkedList class
    /// &lt;/summary&gt;

    [TestFixture]
    public class LinkedList_NUnit
    {

        [Test]
        public void TestLinkedList_add()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Assert.AreEqual(2, Test.Size());
        }
}

The complete LinkedListClass and set of tests are given below:

// LinkedList.cs created with MonoDevelop
// User: martijn at 10:02 AM 12/30/2008

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace LinkedListJavaStyle
{

    /// &lt;summary&gt;
    /// LinkedListElement is the memory structure used by the LinkedList class for storing each list cell.
    /// Every element contains a pointer to the previous and next element and a copy of the data.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;The same as for LinkedList&lt;/typeparam&gt;

    class LinkedListNode&lt;T&gt;
    {
        public T Data;
        public LinkedListNode&lt;T&gt; Prev;
        public LinkedListNode&lt;T&gt; Next;

        public LinkedListNode(T Data)
        {
            this.Data = Data;
        }
    }

    /// &lt;summary&gt;
    /// Linked List implementation following the model layed out by the Java LinkedList Class. Implements all list operations and permits
    /// all elements (including null). Operations that need to enter the list will travel through the list from beginning to end until
    /// the required offset is found (or from the tail if the distance is shorter).
    ///
    /// The class is implemented as a double linked list.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;This class accepts any type you would like to use for the generic.&lt;/typeparam&gt;

    class LinkedList&lt;T&gt;
    {

        LinkedListNode&lt;T&gt; Head;
        LinkedListNode&lt;T&gt; Tail;
        int LinkedList_Size;

        /// ---------------------------------------------------------------------------------------
        /// &lt;summary&gt;
        /// Constructor
        /// &lt;/summary&gt;

        public LinkedList()
        {
            Head = null;
            Tail = null;
            LinkedList_Size = 0;
        }

        /// &lt;summary&gt;
        /// Constructs a list containing the elements of the specified collection, in the order that they are
        /// returned by the collections itterator.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;collection&quot;&gt;An array of type T containing the elements to be added to the list&lt;/param&gt;

        public LinkedList(T[] collection)
        {
            Head = null;
            Tail = null;
            LinkedList_Size = 0;
            AddAll_Internal(Tail, collection);
        }

        /// &lt;summary&gt;
        /// Private function which inserts a T element before the offset given in the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;offset&quot;&gt;A LinkedListElement before which the new elements needs to be inserted&lt;/param&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element to be inserted&lt;/param&gt;
        /// &lt;returns&gt;A reference to the newly created LinkedListElement&lt;/returns&gt;

        private LinkedListNode&lt;T&gt; Add_Internal_Before(LinkedListNode&lt;T&gt; offset, T element)
        {
            if (offset == null)
                throw new Exception(&quot;Add_Internal: null is not a valid argument&quot;);

            LinkedListNode&lt;T&gt; Listelement = new LinkedListNode&lt;T&gt;(element);

            Listelement.Prev = offset.Prev;
            Listelement.Next = offset;

            if (offset.Prev != null) offset.Prev.Next = Listelement;
            offset.Prev = Listelement;

            if (offset == Head)
                Head = Listelement;

            LinkedList_Size++;

            return Listelement;
        }

        /// &lt;summary&gt;
        /// Private function which inserts a T element after the offset given in the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;offset&quot;&gt;The LinkedListElement after which we need to insert the new element&lt;/param&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element to be inserted&lt;/param&gt;
        /// &lt;returns&gt;A reference to the newly created LinkListElement&lt;/returns&gt;

        private LinkedListNode&lt;T&gt; Add_Internal_After(LinkedListNode&lt;T&gt; offset, T element)
        {
            if (offset == null)
                throw new Exception(&quot;Add_Internal: null is not a valid argument&quot;);

            LinkedListNode&lt;T&gt; Listelement = new LinkedListNode&lt;T&gt;(element);

            Listelement.Prev = offset;
            Listelement.Next = offset.Next;
            if (offset.Next != null) offset.Next.Prev = Listelement;
            offset.Next = Listelement;

            if (offset == Tail)
                Tail = Listelement;

            LinkedList_Size++;

            return Listelement;
        }

        /// &lt;summary&gt;
        /// Adds the specified element at the specified position in the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Index&quot;&gt;The index at which to insert the element&lt;/param&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element of T to insert&lt;/param&gt;
        /// &lt;returns&gt;True as per Java implementation&lt;/returns&gt;

        public bool Add(int Index, T element)
        {
            if ((Index == 0) &amp;&amp; (Head == null))
                AddFirst(element);
            else
                Add_Internal_Before(Get_Internal(Index), element);
            return true;
        }

        /// &lt;summary&gt;
        /// Adds the element to the end of the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element of type T to insert&lt;/param&gt;

        public void Add(T element)
        {
            if (Head == null)
                AddFirst(element);
            else
                Add_Internal_After(Tail, element);
        }

        /// &lt;summary&gt;
        /// Adds the element at the beginning of the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element to add to the list&lt;/param&gt;

        public void AddFirst(T element)
        {
            LinkedListNode&lt;T&gt; ListElement = new LinkedListNode&lt;T&gt;(element);
            if (Tail == null)
            {
                Tail = ListElement;
            }
            else
            {
                ListElement.Next = Head;
                Head.Prev = ListElement;
            }
            Head = ListElement;
            LinkedList_Size++;
        }

        /// &lt;summary&gt;
        /// Adds the given element to the end of the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;Element to add to the list&lt;/param&gt;

        public void AddLast(T element)
        {
            LinkedListNode&lt;T&gt; Listelement = new LinkedListNode&lt;T&gt;(element);
            if (Head == null)
            {
                Head = Listelement;
            }
            else
            {
                Listelement.Prev = Tail;
                Tail.Next = Listelement;
            }
            Tail = Listelement;
            LinkedList_Size++;
        }

        /// &lt;summary&gt;
        /// Private function which adds all the elements in the given collection to the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;start&quot;&gt;A LinkedListElement giving the starting point in the list&lt;/param&gt;
        /// &lt;param name=&quot;collection&quot;&gt;Elements to add to the list&lt;/param&gt;

        private void AddAll_Internal(LinkedListNode&lt;T&gt; start, T[] collection)
        {
            // The set of elements is inserted before start, but then needs to follow the
            // newly inserted first element.
            bool First = true;
            foreach (T element in collection)
            {
                if (Head == null)
                {
                    AddFirst(element);
                    start = Head;
                    First = false;
                }
                else
                {
                    if (First)
                    {
                        start = Add_Internal_Before(start, element);
                        First = false;
                    }
                    else
                        start = Add_Internal_After(start, element);
                }
            }
        }

        /// &lt;summary&gt;
        /// Adds all the elements in the collection to the end of the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;collection&quot;&gt;An array of T with all the elements to add&lt;/param&gt;

        public void AddAll(T[] collection)
        {
            // Obtain the element at the given offset
            AddAll_Internal(Tail, collection);
        }

        /// &lt;summary&gt;
        /// Adds all the elements in the collection to the list from the end
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;collection&quot;&gt;An array of T with all the elements to add&lt;/param&gt;

        public void AddAll(int index, T[] collection)
        {
            AddAll_Internal(Get_Internal(index), collection);
        }

        /// &lt;summary&gt;
        /// Empties the list by unlinking all elements.
        /// &lt;/summary&gt;

        public void Clear()
        {
            LinkedListNode&lt;T&gt; Temp;

            while (Head != null)
            {
                Temp = Head;
                Head = Head.Next;

                Temp.Prev = null;
                Temp.Next = null;
            }

            Tail = null;
            LinkedList_Size = 0;
        }

        /// &lt;summary&gt;
        /// Returns a copy of the LinkedList containing all the elements.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;A LinkedList of the same type&lt;/returns&gt;

        public LinkedList&lt;T&gt; Clone()
        {
            LinkedList&lt;T&gt; ClonedCopy = new LinkedList&lt;T&gt;();

            LinkedListNode&lt;T&gt; Iterator = Head;
            while (Iterator != null)
            {
                ClonedCopy.AddLast(Iterator.Data);
                Iterator = Iterator.Next;
            }
            return ClonedCopy;
        }

        // Contains
        // Returns true if the list contains the specified element

        public bool Contains(T needle)
        {
            LinkedListNode&lt;T&gt; Iterator = Head;
            while (Iterator != null)
            {
                // Check for null in the needle
                if ((needle == null)&amp;&amp;(Iterator.Data == null))
                  return true;

                // Check for null in the list
                if (Iterator.Data != null)
                    if (Iterator.Data.Equals(needle))
                        return true;

                // Not found, continue to the next entry
                Iterator = Iterator.Next;
            }
            return false;
        }

        /// &lt;summary&gt;
        /// Returns the number of elements in this list
        /// &lt;/summary&gt;
        /// &lt;returns&gt;the number of elements in the list&lt;/returns&gt;

        public int Size()
        {
            return LinkedList_Size;
        }

        /// &lt;summary&gt;
        /// An internal function which travels the list to find the specified index.
        /// The function travels forward/backward depending on whether the head or
        /// tail is closer to the specified index.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Index&quot;&gt;The position in the list to find.&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        private LinkedListNode&lt;T&gt; Get_Internal(int Index)
        {
            if ((LinkedList_Size == 0) || (Index &lt; 0) || (Index &gt;= LinkedList_Size))
                throw new IndexOutOfRangeException(&quot;LinkedList&lt;T&gt; Invalid Index&quot;);

            LinkedListNode&lt;T&gt; iterator;
            int DistanceFromHead = Index;
            int DistanceFromTail = LinkedList_Size - Index -1;  

            if (DistanceFromHead &lt; DistanceFromTail)
            {
                // We travel forward if the index is closer to the beginning
                iterator = Head;
                while (iterator != null &amp;&amp; DistanceFromHead-- &gt; 0)
                    iterator = iterator.Next;
            }
            else
            {
                // We travel backward if the index is closer to the end
                iterator = Tail;
                while (iterator != null &amp;&amp; DistanceFromTail-- &gt; 0)
                    iterator = iterator.Prev;
            }

            return iterator;
        }

        /// &lt;summary&gt;
        /// Returns the value of the specified element in the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;index&quot;&gt;The index item to return&lt;/param&gt;
        /// &lt;returns&gt;The value of the element specified &lt;/returns&gt;
        /// &lt;throws&gt;IndexOutOfBoundsException if the index is out of range (smaller than 0 or index &gt;= size()&lt;/throws&gt;

        public T Get(int index)
        {
            return Get_Internal(index).Data;
        }

        /// &lt;summary&gt;
        /// Returns the value stored at the head of the list
        /// &lt;/summary&gt;
        /// &lt;returns&gt;The value stored at the head of the list&lt;/returns&gt;

        public T GetFirst()
        {
            if (LinkedList_Size == 0)
                throw new IndexOutOfRangeException(&quot;LinkedList&lt;T&gt; Invalid Index&quot;);
            return Head.Data;
        }

        /// &lt;summary&gt;
        /// Returns the value stored at the tail of the list
        /// &lt;/summary&gt;
        /// &lt;returns&gt;The value stored at the tail of the list&lt;/returns&gt;

        public T GetLast()
        {
            if (LinkedList_Size == 0)
                throw new IndexOutOfRangeException(&quot;LinkedList&lt;T&gt; Invalid Index&quot;);
            return Tail.Data;
        }

        /// &lt;summary&gt;
        /// Search for the given element in the list and return the LinkedListNode
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;Element to search for&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        private LinkedListNode&lt;T&gt; IndexOf_Internal(T element)
        {
            int Index = 0;
            LinkedListNode&lt;T&gt; Iterator = Head;
            while (Iterator != null)
            {
                // Check for null in the needle
                if ((element == null) &amp;&amp; (Iterator.Data == null))
                    return Iterator;

                // Check for null in the list
                if (Iterator.Data != null)
                    if (Iterator.Data.Equals(element))
                        return Iterator;

                Index++;
                Iterator = Iterator.Next;
            }
            return null;
        }

        /// &lt;summary&gt;
        /// This routine searches the linked list for the first occurance of the specified element
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;The value to look for, null is also possible&lt;/param&gt;
        /// &lt;returns&gt;The index of the item searched, or -1 if not found&lt;/returns&gt;

        public int IndexOf(T element)
        {
            int Index = 0;
            LinkedListNode&lt;T&gt; Iterator = Head;
            while (Iterator != null)
            {
                // Check for null in the needle
                if ((element == null) &amp;&amp; (Iterator.Data == null))
                    return Index;

                // Check for null in the list
                if (Iterator.Data != null)
                    if (Iterator.Data.Equals(element))
                        return Index;

                Index++;
                Iterator = Iterator.Next;
            }
            return -1;
        }

        /// &lt;summary&gt;
        /// Returns the last occurance of the specified element in the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;The value to search for&lt;/param&gt;
        /// &lt;returns&gt;The index of the element, or -1 if not found&lt;/returns&gt;

        public int LastIndexOf(T element)
        {
            int Index = LinkedList_Size;
            LinkedListNode&lt;T&gt; Iterator = Tail;
            while (Iterator != null)
            {
                Index--;

                // Check for null in the element
                if ((element == null) &amp;&amp; (Iterator.Data == null))
                    return Index;

                // Check for null in the list before checking the content
                if (Iterator.Data != null)
                    if (Iterator.Data.Equals(element))
                        return Index;

                Iterator = Iterator.Prev;
            }
            return -1;
        }

        /// &lt;summary&gt;
        /// An internal function which unlinks a specified link in the list chain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;A reference to the list item to unlink&lt;/param&gt;

        public void Remove_Internal(LinkedListNode&lt;T&gt; element)
        {
            if (element == null)
                throw new Exception(&quot;LinkedListNode&lt;T&gt; null is not a valid argument&quot;);

            if (element == Head)
                Head = element.Next;

            if (element == Tail)
                Tail = element.Prev;

            if (element.Prev != null)
                element.Prev.Next = element.Next;

            if (element.Next != null)
                element.Next.Prev = element.Prev;

            LinkedList_Size--;
        }

        /// &lt;summary&gt;
        /// This function removes the specified index item from the list
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Index&quot;&gt;&lt;/param&gt;
        /// &lt;throws&gt;IndexOutOfRangeException if an invalid index is given&lt;/throws&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        public T Remove(int Index)
        {
            LinkedListNode&lt;T&gt; Element = Get_Internal(Index);

            T Data = Element.Data;

            Remove_Internal(Element);

            return Data;
        }

        /// &lt;summary&gt;
        /// Searches the list for the first occurance of the specified element, and removes it.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;Element to remove&lt;/param&gt;
        /// &lt;returns&gt;True if the element was found and removed, False if not found&lt;/returns&gt;

        public bool Remove(T element)
        {
            LinkedListNode&lt;T&gt; Node = IndexOf_Internal(element);

            // Find the element offset
            if (Node != null)
            {
                // This is bad -- we walk the list twice -- need to optimize
                Remove_Internal(Node);
                return true;
            }

            return false;
        }

        /// &lt;summary&gt;
        /// This routine removes the first element from the list
        /// &lt;/summary&gt;
        /// &lt;returns&gt;The value of the element removed&lt;/returns&gt;
        /// &lt;throws&gt;IndexOutofRangException if the list is empty&lt;/throws&gt;

        public T RemoveFirst()
        {
            if (LinkedList_Size == 0)
                throw new IndexOutOfRangeException(&quot;LinkedList&lt;T&gt; Empty List&quot;);

            T Data = Head.Data;

            Remove_Internal(Head);

            return Data;
        }

        /// &lt;summary&gt;
        /// Remove the last element of the list
        /// &lt;/summary&gt;
        /// &lt;returns&gt;The value of the element removed&lt;/returns&gt;
        /// &lt;throws&gt;IndexOutofRangException if the list is empty&lt;/throws&gt;

        public T RemoveLast()
        {
            if (LinkedList_Size == 0)
                throw new IndexOutOfRangeException(&quot;LinkedList&lt;T&gt; Empty List&quot;);

            T Data = Tail.Data;

            Remove_Internal(Tail);

            return Data;
        }

        /// &lt;summary&gt;
        /// This routine inserts the given element at the given index
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Index&quot;&gt;The index to insert the element at&lt;/param&gt;
        /// &lt;param name=&quot;element&quot;&gt;The element to insert&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        public T Set(int Index, T element)
        {
            LinkedListNode&lt;T&gt; OldListEntry = Get_Internal(Index);

            // Keep a pointer to the old data object
            T Temp = OldListEntry.Data;

            // Swap it with the new data object
            OldListEntry.Data = element;

            // And return the old one
            return Temp;
        }

        /// &lt;summary&gt;
        /// Returns an array containing all the elements in the list in the head-tail order
        /// &lt;/summary&gt;
        /// &lt;returns&gt;An array of T[] containing all the elements in the list&lt;/returns&gt;

        public T[] ToArray()
        {
            LinkedListNode&lt;T&gt; iterator = Head;
            T[] DataArray = new T[LinkedList_Size];
            int Index = 0;

            while (iterator != null)
            {
                DataArray[Index++] = iterator.Data;
                iterator = iterator.Next;
            }

            return DataArray;
        }

        /// &lt;summary&gt;
        /// Returns a list iterator of the elements in this list implementing the IENumerator interface.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;IENumerator &lt;/returns&gt;

        public IEnumerator&lt;T&gt; GetEnumerator()
        {
            return new LinkedListEnumerator(this);
        }

        /// &lt;summary&gt;
        /// The LinkedListEnumerator is an nested class implementing the IENumerator interface. Making it
        /// possible to call foreach() on the list.
        /// &lt;/summary&gt;

        class LinkedListEnumerator : IEnumerator&lt;T&gt;
        {
            LinkedListNode&lt;T&gt; start;
            LinkedListNode&lt;T&gt; current;

            public LinkedListEnumerator(LinkedList&lt;T&gt; list)
            {
                start = list.Head;
                current = null;
            }
            public bool MoveNext()
            {
                if (current == null) current = start;
                else current = current.Next;
                return (current != null);
            }

            public T Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            object IEnumerator.Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            public void Dispose() { }
            public void Reset() { current = null; }
        }

    }

}
</pre>
<p><strong>LinkedList_NUnit.cs</strong></p>
<pre class="brush: c#">
using System;
using System.Text;
using NUnit.Framework;

namespace LinkedListJavaStyle
{
    /// &lt;summary&gt;
    /// LinkedList_NUnit is a class implementing a set of unit tests for each of the methods supported by the LinkedList class
    /// &lt;/summary&gt;

    [TestFixture]
    public class LinkedList_NUnit
    {

        [TestX]
        public void TestLinkedList_add()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Assert.AreEqual(2, Test.Size());
        }

        [Test]
        public void TestLinkedList_Add_AtIndex()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Test.Add(&quot;Boom Boom&quot;);
            Test.Add(2, &quot;Much Wiser&quot;);
            Assert.AreEqual(4, Test.Size());
            string Value = Test.Get(2);
            Assert.AreEqual(&quot;Much Wiser&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Add_AtFirst()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Test.AddFirst(&quot;Much Wiser&quot;);
            Assert.AreEqual(3, Test.Size());
            string Value = Test.Get(0);
            Assert.AreEqual(&quot;Much Wiser&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Add_AtLast()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            Test.Add(&quot;Hello World&quot;);
            Test.Add(&quot;The world today&quot;);
            Test.AddLast(&quot;Much Wiser&quot;);
            Assert.AreEqual(3, Test.Size());
            string Value = Test.Get(2);
            Assert.AreEqual(&quot;Much Wiser&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Add_All()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            Assert.AreEqual(3, Test.Size());
            string Value = Test.Get(1);
            Assert.AreEqual(&quot;The World Today&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Add_AllFromIndex()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            string[] Input2 = { &quot;Monty Python&quot;, &quot;Flying Circus&quot; };
            Test.AddAll(Input);
            Assert.AreEqual(3, Test.Size());
            Test.AddAll(1, Input2);
            string Value = Test.Get(2);
            Assert.AreEqual(&quot;Flying Circus&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Clear()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            Test.Clear();
            Assert.AreEqual(0, Test.Size());
        }

        [Test]
        public void TestLinkedList_Clone()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            LinkedList&lt;string&gt; Test2;
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            Test2 = Test.Clone();
            Test.Clear();
            Assert.AreEqual(3, Test2.Size());
            string Value = Test2.Get(1);
            Assert.AreEqual(&quot;The World Today&quot;, Value);
        }

        [Test]
        public void TestLinkedList_Contains()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, null, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            Assert.IsTrue(Test.Contains(&quot;Hello World&quot;));
            Assert.IsFalse(Test.Contains(&quot;Botany Bay&quot;));
            Assert.IsTrue(Test.Contains(null));
        }

        [Test]
        public void TestLinkedList_Get()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            string Value = Test.Get(2);
            Assert.AreEqual(&quot;Much Wiser&quot;, Value);
            Assert.
        }

        [Test]
        public void TestLinkedList_GetFirst()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            string Value = Test.GetFirst();
            Assert.AreEqual(&quot;Hello World&quot;, Value);
        }

        [Test]
        public void TestLinkedList_GetLast()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            string Value = Test.GetLast();
            Assert.AreEqual(&quot;Much Wiser&quot;, Value);
        }

        [Test]
        public void TestLinkedList_IndexOf()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, null, &quot;Much Wiser&quot; };
            Test.AddAll(Input);
            int IndexValue = Test.IndexOf(&quot;The World Today&quot;);
            Assert.AreEqual(1, IndexValue);
            int IndexValue2 = Test.IndexOf(&quot;My Day In the Sun&quot;);
            Assert.AreEqual(-1, IndexValue2);
            int IndexValue3 = Test.IndexOf(null);
            Assert.AreEqual(2, IndexValue3);
        }

        [Test]
        public void TestLinkedList_LastIndexOf()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, null, &quot;Hello World&quot;, null };
            Test.AddAll(Input);
            int IndexValue = Test.LastIndexOf(&quot;Hello World&quot;);
            Assert.AreEqual(3, IndexValue);
            int IndexValue2 = Test.LastIndexOf(&quot;My Day In the Sun&quot;);
            Assert.AreEqual(-1, IndexValue2);
            int IndexValue3 = Test.LastIndexOf(null);
            Assert.AreEqual(4, IndexValue3);
        }

        [Test]
        public void TestLinkedList_listIterator()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            // The array is empty, and we should never enter this part
            foreach (string token in Test)
                Assert.Fail(&quot;Entered empty iterator&quot;);

            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Hello World&quot; };

            Test.AddAll(Input);

            // Match the contents against the string[]
            int offset = 0;
            foreach (string token in Test)
                Assert.AreEqual(token, Input[offset++]);
        }

        [Test]
        public void TestLinkedList_remove()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot; };
            Test.AddAll(Input);
            Test.Remove(1);
            // There are only 2 elements left
            Assert.AreEqual(Test.Size(), 2);
            // Before the removal this was Position 2
            int IndexValue1 = Test.IndexOf(&quot;Its going to be a fine day&quot;);
            Assert.AreEqual(IndexValue1, 1);
        }

        [Test]
        public void TestLinkedList_RemoveObject()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot; };
            Test.AddAll(Input);
            Assert.AreEqual(Test.Remove(&quot;Its going to be a fine day&quot;), true);
            // There are only 2 elements left
            Assert.AreEqual(Test.Size(), 2);
            // We should not be able to find this element
            Assert.AreEqual(Test.IndexOf(&quot;Its going to be a fine day&quot;), -1);
        }

        [Test]
        public void TestLinkedList_removeFirst()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot; };
            Test.AddAll(Input);
            Test.RemoveFirst();
            // There are only 2 elements left
            Assert.AreEqual(Test.Size(), 2);
            // Before the removal this was Position 1
            int IndexValue1 = Test.IndexOf(&quot;The World Today&quot;);
            Assert.AreEqual(IndexValue1, 0);
        }

        [Test]
        public void TestLinkedList_removeLast()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot; };
            Test.AddAll(Input);

            // We should not be able to find this now
            int IndexValue1 = Test.IndexOf(&quot;Its going to be a fine day&quot;);
            Assert.AreEqual(IndexValue1, 2);

            // Remove the last entry
            Test.RemoveLast();

            // There are only 2 elements left
            Assert.AreEqual(Test.Size(), 2);

            // We should not be able to find this now
            int IndexValue2 = Test.IndexOf(&quot;Its going to be a fine day&quot;);
            Assert.AreEqual(IndexValue2, -1);
        }

        [Test]
        public void TestLinkedList_Set()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot; };
            Test.AddAll(Input);

            // Replace position #1 with a new object
            string OldValue = Test.Set(1, &quot;Sunday Sports&quot;);
            Assert.AreEqual(OldValue, &quot;The World Today&quot;);

            int IndexValue2 = Test.IndexOf(&quot;Sunday Sports&quot;);
            Assert.AreEqual(IndexValue2, 1);
        }

        [Test]
        public void TestLinkedList_ToArray()
        {
            LinkedList&lt;string&gt; Test = new LinkedList&lt;string&gt;();
            string[] Input = { &quot;Hello World&quot;, &quot;The World Today&quot;, &quot;Its going to be a fine day&quot;, null };
            Test.AddAll(Input);

            string[] Copy = Test.ToArray();

            int Index = 0;
            foreach (string element in Input)
                Assert.AreEqual(element, Copy[Index++]);
        }

    }

}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/using-linked-lists-in-c-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using linked lists in C# &#8211; Part I</title>
		<link>http://www.dijksterhuis.org/using-linked-lists-in-c-part-i/</link>
		<comments>http://www.dijksterhuis.org/using-linked-lists-in-c-part-i/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 08:39:39 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=396</guid>
		<description><![CDATA[There is re-markedly little honor in building your own linked list class in C#. The standard libraries provide a solid implementation in the LinkedList generic class. The point of languages such as C# and Java is of course that code re-use should be the top priority, so why re-invent one of the most elementary wheels [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>There is re-markedly little honor in building your own linked list class in C#. The standard libraries provide a solid implementation in the LinkedList<T> generic class. The point of languages such as C# and Java is of course that code re-use should be the top priority, so why re-invent one of the most elementary wheels of computer science? In this post I will look at why you could use a linked list, and how they work.</em></p>
<p><span id="more-396"></span></p>
<p>If you don&#8217;t know in advance how many elements you are going to store a linked list is often a good solution. But what is a linked list anyway? I</p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/doublelinkedlist.png" alt="Double Linked List" title="Double Linked List" width="391" height="141" class="alignnone size-full wp-image-398" /></p>
<p>In a linked list every element is linked to the next element in the list. If you would like to add a new element, you just allocate the memory for the new element and add it to the chain. So at the price of a little overhead (the need to keep links) you are prepared for situations that might grow from just 1 or 2 items to huge numbers of elements.</p>
<p>A common alternative is to allocate an array and allow it to grow when it reaches maximum capacity. This incurs a processing penalty as new memory needs to be allocated and the old array is copied to the new array.</p>
<p>For the linked list the penalty comes in access speed. In an array you can immediately access every element through <em>my_array[1], my_array[1000]</em> etc. In a linked list you have to start at the top and step through the whole list until the element is found. One optimization you can make here is to keep a counter of elements. If you know that the element you are looking for is closer to the end you could start at the end of the list, and count backwards.</p>
<p>Another benefit of linked lists is that it is possible to remove elements, something that is very hard to do in arrays. An array with many empty elements becomes wasteful and would require repacking or shrinking. </p>
<p>The following code implements a simple linked list using C# generics.</p>
<p>First we need to define the link elements in C# we use a <em>class</em> for this, not a <em>struct</em>. The reason being that classes in C# are passed by reference. If you make a copy of a reference, just the reference is copied, not the original item (which is just like using pointers in C and C++)  If we were to use a <em>struct</em> each action would involve copying the whole item as structs are passed by value.</p>
<pre class="brush: c#">
    class LinkedListElement&lt;T&gt;
    {
        public T Data;
        public LinkedListElement&lt;T&gt; Prev;
        public LinkedListElement&lt;T&gt; Next;

        public LinkedListElement(T Data)
        {
            this.Data = Data;
        }
    }
</pre>
<p>As you can see from the above definition we will be using a double-linked list: we keep a reference to both the previous and next item in the list. The benefit of this is that is it possible to travel through the list both in directions. In a single linked list, we would only have a reference to the next item, but not to the previous one. It also makes it easier to remove elements from the list. </p>
<pre class="brush: c#">
    class LinkedList&lt;T&gt;
    {
        public LinkedListElement&lt;T&gt; Head;
        public LinkedListElement&lt;T&gt; Tail;

        public LinkedList()
        {
            Head = null;
            Tail = null;
        }
    }
</pre>
<p>In the double linked list we keep a reference to both the Head and Tail of the list. In an empty list, both the Head and Tail are NULL.  If the list contains only one element, both Head and Tail point to the same element. For the Head element, the previous element is always NULL. For the Tail element the next element is always NULL.</p>
<pre class="brush: c#">
        public void Add(T element)
        {
            LinkedListElement&lt;T&gt; Listelement = new LinkedListElement&lt;T&gt;(element);
            if (Head == null)
            {
                Head = Listelement;
            }
            else
            {
                Listelement.Prev = Tail;
                Tail.Next = Listelement;
            }
            Tail = Listelement;
        }
</pre>
<p>In adding to the list we need to check if the list is empty, if it is, the new element becomes the head.Otherwise we will add the new element to the end of the tail.</p>
<pre class="brush: c#">
        public void Remove(LinkedListElement&lt;T&gt; element)
        {
            if (element == null)
                throw new Exception(&quot;LinkedListElement&lt;T&gt; null is not a valid argument&quot;);

            if (element == Head)
                Head = element.Next;
            if (element == Tail)
                Tail = element.Prev;

            if (element.Prev != null)
            {
                LinkedListElement&lt;T&gt; prev = element.Prev;
                prev.Next = element.Next;
            }
            if (element.Next != null)
            {
                LinkedListElement&lt;T&gt; next = element.Next;
                next.Prev = element.Prev;
            }
        }
</pre>
<p>Removing an element from the list involves fusing the previous element and next element together. And of course we need to check if it the element removed is the head or tail element.</p>
<p>The last basic action of using a list is to find if an element is stored in the list.</p>
<pre class="brush: c#">
        public LinkedListElement&lt;T&gt; Find(T needle)
        {
            return Find(needle, Head);
        }

        public LinkedListElement&lt;T&gt; Find(T needle, LinkedListElement&lt;T&gt; start)
        {
            LinkedListElement&lt;T&gt; iterator = start;
            while (iterator != null)
            {
                if (iterator.Data.Equals(needle)) return iterator;
                iterator = iterator.Next;
            }
            return null;
        }
</pre>
<p>A simple iterator loops through the list comparing the linked list element to the one you are looking for, starting from the head of the list.</p>
<p>The full code of the linked list implementation is listed below.  There is still much that it can be improved upon. C# provides a standard iterator mechanism, which is easy to implement and would make it possible to use our linked list in a <em>forearch</em> loop. That would also remove the need to expose so much of the classes internals to the outside world. A better implementation would hide the internal use of LinkedListElement<T> completely.</p>
<p>In my next post I will show an implementation of Java inspired LinkedList class in C# which improves on the above problems.</p>
<pre class="brush: c#">
using System;

namespace LinkedList_Simple
{

    class LinkedListElement&lt;T&gt;
    {
        public T Data;
        public LinkedListElement&lt;T&gt; Prev;
        public LinkedListElement&lt;T&gt; Next;

        public LinkedListElement(T Data)
        {
            this.Data = Data;
        }
    }

    class LinkedList&lt;T&gt;
    {

        public LinkedListElement&lt;T&gt; Head;
        public LinkedListElement&lt;T&gt; Tail;

        public LinkedList()
        {
            Head = null;
            Tail = null;
        }

        public void Add(T element)
        {
            LinkedListElement&lt;T&gt; Listelement = new LinkedListElement&lt;T&gt;(element);
            if (Head == null)
            {
                Head = Listelement;
            }
            else
            {
                Listelement.Prev = Tail;
                Tail.Next = Listelement;
            }
            Tail = Listelement;
        }

        public LinkedListElement&lt;T&gt; Next(LinkedListElement&lt;T&gt; element)
        {
            if (element == null)
                throw new Exception(&quot;LinkedListElement&lt;T&gt; null is not a valid argument&quot;);
            return element.Next;
        }

        public LinkedListElement&lt;T&gt; Prev(LinkedListElement&lt;T&gt; element)
        {
            if (element == null)
                throw new Exception(&quot;LinkedListElement&lt;T&gt; null is not a valid argument&quot;);
            return element.Prev;
        }

        public void Remove(LinkedListElement&lt;T&gt; element)
        {
            if (element == null)
                throw new Exception(&quot;LinkedListElement&lt;T&gt; null is not a valid argument&quot;);

            if (element == Head)
                Head = element.Next;
            if (element == Tail)
                Tail = element.Prev;

            if (element.Prev != null)
            {
                LinkedListElement&lt;T&gt; prev = element.Prev;
                prev.Next = element.Next;
            }
            if (element.Next != null)
            {
                LinkedListElement&lt;T&gt; next = element.Next;
                next.Prev = element.Prev;
            }
        }

        public LinkedListElement&lt;T&gt; Find(T needle)
        {
            return Find(needle, Head);
        }

        public LinkedListElement&lt;T&gt; Find(T needle, LinkedListElement&lt;T&gt; start)
        {
            LinkedListElement&lt;T&gt; iterator = start;
            while (iterator != null)
            {
                if (iterator.Data.Equals(needle)) return iterator;
                iterator = iterator.Next;
            }
            return null;
        }

    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            LinkedList&lt;string&gt; myList = new LinkedList&lt;string&gt;();
            myList.Add(&quot;Hello World&quot;);
            myList.Add(&quot;Good day to you&quot;);
            myList.Add(&quot;Once upon a time in the west&quot;);

            LinkedListElement&lt;string&gt; search_it = myList.Find(&quot;Good day to you&quot;);

            if (search_it != null)
            {
                Console.WriteLine(&quot;Found: {0}&quot;, search_it.Data);
                myList.Remove(search_it);
            }
            else
                Console.WriteLine(&quot;Not found!&quot;);

            // Print the contents of the entire list
            LinkedListElement&lt;string&gt; print_it = myList.Head;

            int Lp = 0;
            while (print_it != null)
            {
                Console.WriteLine(&quot;{0} {1}&quot;, Lp++, print_it.Data);
                print_it = myList.Next(print_it);
            }

        }
    }

}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/using-linked-lists-in-c-part-i/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implementing a Generic Binary Tree in C#</title>
		<link>http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/</link>
		<comments>http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 04:41:05 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=350</guid>
		<description><![CDATA[This post looks at how to implement a binary tree using generics in C#. A binary tree is a data structure in which each node has at most two children. They are a good way to store unsorted data, as the data becomes sorted as you insert it into the tree. 
Another benefit of storing [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>This post looks at how to implement a binary tree using generics in C#. A binary tree is a data structure in which each node has at most two children. They are a good way to store unsorted data, as the data becomes sorted as you insert it into the tree. </p>
<p>Another benefit of storing information in a tree structure is the opportunity for faster search times. In an array (or list) you need to traverse the whole array to discover if it contains a particular value. A well-balanced binary tree can drastically reduce the number of look-ups required. </em></p>
<p><span id="more-350"></span></p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/binarytree_example.gif" alt="" title="Binary Tree Example" width="500" height="280" class="alignnone size-full wp-image-351" /></p>
<p>Given the left set of numbers, the tree on the right is created. If a value is smaller than the root, it goes left, if a value is larger it goes right. If both the left and right nodes have been assigned already, we need to travel further down the tree and create new entries there.</p>
<p>In the tree above the longest route from the root of the tree (5) is to discover that it contains (6) which in this example takes just 4 steps. All other values can be found in 1-3 steps.</p>
<p><strong>Balancing the tree</strong></p>
<p>Several algorithms exist for balancing trees &#8212; but in this post we keep things simple: our tree does not balance itself as new values are inserted.</p>
<p>By re-balancing it is possible to ensure that the maximum depth of the tree stays constant. If we were to insert data in-order into the tree, the tree itself would become lopsided and that would reduce its use in searching. The greater the trees depth (maximum number of steps from the root) the longer a potential search would take, and in the most unfortunate instance it would be the same as for a linked list or array.</p>
<p>So to maximize this trees potential we would need our data insertion to be as random as possible.</p>
<p><strong>The Tree Node Structure</strong></p>
<p>Each node in our tree can be described by a very simple class:</p>
<pre class="brush: c#">
       class BinaryTreeNode
        {
            public BinaryTreeNode Left;
            public BinaryTreeNode Right;
            public BinaryTreeNode Parent;
            public T Data;

            public BinaryTreeNode()
            {
                Left = null;
                Right = null;
                Parent = null;
            }
        }
</pre>
<p>We use a class, and not a struct as C# passes classes by reference, and structs by value. Passing by reference is the same as using pointers in C/C++. It allows us to dynamically add new entries &#8212; or remove them &#8212;  and to traverse the tree.</p>
<p>Each node has the potential to link to another Left and Right node and it stores one Data unit.</p>
<p>Because we will be traveling through the tree non-recursively we also need to keep a link to the Parent node. This allows us to travel back up the tree if we have reached a dead end in our search.</p>
<p><strong>Using Generics in a Binary Tree</strong></p>
<p>To allow us to store any kind of data &#8212; not just integers, the actual Binary Tree class is implemented using Generics. You are free to define your own datastructure and store it in the tree.</p>
<blockquote><p>class BinaryTree&lt;T&gt;</p></blockquote>
<p>But how to sort our data? Because T can be anything, the compiler does not know how to compare two instances of T to each other. For our tree algorithm we need to know if:</p>
<blockquote><p>T1 < T2<br />
T1 == T2<br />
T1 > T2
</p></blockquote>
<p>Generic sorting routines have the same problem, and the System class of C# provides a delegate function that we will use in our tree:</p>
<pre class="brush: c#">
public delegate int Comparison&lt;T&gt;(T x,T y)
</pre>
<p>A sample implementation for comparing integers is provided in the class:</p>
<pre class="brush: c#">
        /// &lt;summary&gt;
        /// For integer comparisons we provide a demonstration function.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&amp;lt;0 for left smaller than right, &amp;gt;0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_Int(int left, int right)
        {
            return left - right;
        }
</pre>
<p>This function is passed to the class constructor on creation:</p>
<pre class="brush: c#">
         BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);
</pre>
<p>If you use your own data type you will have to provide your own comparison function.</p>
<p><strong>Insert Algorithm</strong></p>
<p>Most of the work of building the tree is done in the insert algorithm.</p>
<p>The flowchart is a little long to insert in a blog post, but if you are interested you can <a href="http://www.dijksterhuis.org/wp-content/uploads/2008/12/flowchart_add.gif">find it here</a>.</p>
<p><strong>Custom Iterator</strong></p>
<p>To retrieve all the values from the binary tree the BinaryTree class provides a custom iterator. The iterator it returns performs an ordered walk through the binary tree returning each data entry stored in order of increasing value.</p>
<pre class="brush: c#">
            BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);

             /*...*/

            // Iterate over all members in the tree -- values are returned in sorted order
            foreach(int value in Test)
            {
                Console.WriteLine(&quot;Value: {0}&quot;, value);
            }
</pre>
<p>The code for the BinaryTree class is listed below, a small set of test routines is given in the TreeTest class.</p>
<pre class="brush: c#">
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Developer.Collections
{

    /// &lt;summary&gt;
    /// The BinaryTree class implements a simple non-balanced sorted Binary Tree in C#
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;The tree can contain any type, but you are required to provide your own comparison function.&lt;/typeparam&gt;

    class BinaryTree&lt;T&gt;
    {
        /// &lt;summary&gt;
        /// The tree is build up out of BinaryTreeNode instances
        /// &lt;/summary&gt;

        class BinaryTreeNode
        {
            public BinaryTreeNode Left;
            public BinaryTreeNode Right;
            public BinaryTreeNode Parent;
            public T Data;

            public BinaryTreeNode()
            {
                Left = null;
                Right = null;
                Parent = null;
            }
        }

        BinaryTreeNode Root;
        Comparison&lt;T&gt; CompareFunction;

        /// &lt;summary&gt;
        /// The BinaryTree constructor requires that we pass a comparison function. We need one as generics can only
        /// be compared as equals, but not for order. The solution is to allow the caller to pass a suitable comparison
        /// function. We use the C# Comparison delegate for this (found in System.Collections)
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;theCompareFunction&quot;&gt;Pass a delegate function of the type Comparison to the function&lt;/param&gt;

        public BinaryTree(Comparison&lt;T&gt; theCompareFunction)
        {
            Root = null;
            CompareFunction = theCompareFunction;
        }

        /// &lt;summary&gt;
        /// For integer comparisons we provide a demonstration function.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&amp;lt;0 for left smaller than right, &amp;gt;0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_Int(int left, int right)
        {
            return left - right;
        }

        /// &lt;summary&gt;
        /// For string comparisons we provide a demonstration function
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;-1 for left smaller than right, 0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_String(string left, string right)
        {
            return left.CompareTo(right);
        }

        /// &lt;summary&gt;
        /// The add function uses non-recursive tree traversal to find the next available insertion point
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Value&quot;&gt;The value to insert into tree.&lt;/param&gt;

        public void Add(T Value)
        {
            BinaryTreeNode child = new BinaryTreeNode();
            child.Data = Value;

            // Is the tree empty? Make the root the new child
            if (Root == null)
            {
                Root = child;
            }
            else
            {
                // Start from the root of the tree
                BinaryTreeNode Iterator = Root;
                while (true)
                {
                    // Compare the value to insert with the value in the current tree node
                    int Compare = CompareFunction(Value, Iterator.Data);
                    // The value is smaller or equal to the current node, we need to store it on the left side
                    // We test for equivalence as we allow duplicates (!)
                    if (Compare &lt;= 0)
                        if (Iterator.Left != null)
                        {
                            // Travel further left
                            Iterator = Iterator.Left;
                            continue;
                        }
                        else
                        {
                            // An empty left leg, add the new node on the left leg
                            Iterator.Left = child;
                            child.Parent = Iterator;
                            break;
                        }
                    if (Compare &gt; 0)
                        if (Iterator.Right != null)
                        {
                            // Continue to travel right
                            Iterator = Iterator.Right;
                            continue;
                        }
                        else
                        {
                            // Add the child to the right leg
                            Iterator.Right = child;
                            child.Parent = Iterator;
                            break;
                        }
                }

            }

        }

        /// &lt;summary&gt;
        /// This routine walks through the tree to see if the value given can be found.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Value&quot;&gt;The value to look for in the tree&lt;/param&gt;
        /// &lt;returns&gt;True if found, False if not found&lt;/returns&gt;

        public bool Find(T Value)
        {
            BinaryTreeNode Iterator = Root;
            while (Iterator != null)
            {
                int Compare = CompareFunction(Value, Iterator.Data);
                // Did we find the value ?
                if (Compare == 0) return true;
                if (Compare &lt; 0)
                {
                    // Travel left
                    Iterator = Iterator.Left;
                    continue;
                }
                // Travel right
                Iterator = Iterator.Right;
            }
            return false;
        }

        /// &lt;summary&gt;
        /// Given a starting node, this routine will locate the left most node in the sub-tree
        /// If no further nodes are found, it returns the starting node
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;start&quot;&gt;The sub-tree starting point&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        BinaryTreeNode FindMostLeft(BinaryTreeNode start)
        {
            BinaryTreeNode node = start;
            while (true)
            {
                if (node.Left != null)
                {
                    node = node.Left;
                    continue;
                }
                break;
            }
            return node;
        }

        /// &lt;summary&gt;
        /// Returns a list iterator of the elements in the tree implementing the IENumerator interface.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;IENumerator&lt;/returns&gt;

        public IEnumerator&lt;T&gt; GetEnumerator()
        {
            return new BinaryTreeEnumerator(this);
        }

        /// &lt;summary&gt;
        /// The BinaryTreeEnumerator implements the IEnumerator allowing foreach enumeration of the tree
        /// &lt;/summary&gt;

        class BinaryTreeEnumerator : IEnumerator&lt;T&gt;
        {
            BinaryTreeNode current;
            BinaryTree&lt;T&gt; theTree;

            public BinaryTreeEnumerator(BinaryTree&lt;T&gt; tree)
            {
                theTree = tree;
                current = null;
            }

            /// &lt;summary&gt;
            /// The MoveNext function traverses the tree in sorted order.
            /// &lt;/summary&gt;
            /// &lt;returns&gt;True if we found a valid entry, False if we have reached the end&lt;/returns&gt;
            public bool MoveNext()
            {
                // For the first entry, find the lowest valued node in the tree
                if (current == null)
                    current = theTree.FindMostLeft(theTree.Root);
                else
                {
                    // Can we go right-left?
                    if (current.Right != null)
                        current = theTree.FindMostLeft(current.Right);
                    else
                    {
                        // Note the value we have found
                        T CurrentValue = current.Data;

                        // Go up the tree until we find a value larger than the largest we have
                        // already found (or if we reach the root of the tree)
                        while (current != null)
                        {
                            current = current.Parent;
                            if (current != null)
                            {
                                int Compare = theTree.CompareFunction(current.Data,CurrentValue);
                                if (Compare &lt; 0) continue;
                            }
                            break;
                        }

                    }
                }
                return (current != null);
            }

            public T Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            object IEnumerator.Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            public void Dispose() { }
            public void Reset() { current = null; }
        }

    }

    class TreeTest
    {
        static void Main(string[] args)
        {
            BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);

            // Build the tree
            Test.Add(5);
            Test.Add(2);
            Test.Add(1);
            Test.Add(3);
            Test.Add(3); // Duplicates are OK
            Test.Add(4);
            Test.Add(6);
            Test.Add(10);
            Test.Add(7);
            Test.Add(8);
            Test.Add(9);

            // Test if we can find values in the tree
            for (int Lp = 1; Lp &lt;= 10; Lp++)
                Console.WriteLine(&quot;Find ({0}) = {1}&quot;, Lp,Test.Find(Lp));

            // Test if we can find a non-existing value
            Console.WriteLine(&quot;Find (999) = {0}&quot;, Test.Find(999));

            // Iterate over all members in the tree -- values are returned in sorted order
            foreach(int value in Test)
            {
                Console.WriteLine(&quot;Value: {0}&quot;, value);
            }

        }
    }

}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating salted hash passwords in C#</title>
		<link>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/</link>
		<comments>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 04:59:11 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[crc]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[salted]]></category>
		<category><![CDATA[sha-1]]></category>
		<category><![CDATA[sha-256]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=336</guid>
		<description><![CDATA[
Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length. [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/salt.jpg" alt="" title="Salted Hash Passwords in C#" width="500" height="288" class="alignnone size-full wp-image-340" /><br />
<em>Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length.  </p>
<p>This article will go into how to create a hash of your passwords and how salting them makes them more secure.</em></p>
<p><span id="more-336"></span></p>
<p><strong>What is a hash?</strong></p>
<p>A hash function turns &#8220;Hello World&#8221; into &#8220;3964322768&#8243;. And it does that every time you run that same string through the hash function. How it does that depends on the hash algorithm, and so does the &#8220;3964322768&#8243; result. </p>
<p>Different hash function return different results, but given the same data the same function always returns the same result. </p>
<p>Now imagine transferring a block of 2Kb of data across the Internet &#8212; at the end of it you include an extra hash. The receiver can check if the data received was all transferred correctly, if a bit had fallen over the data block would have generated a different hash. </p>
<p><strong>On collisions</strong></p>
<p>In the &#8220;old days&#8221; CRC16 was used to ensure that data was being transmitted correctly over telephone and serial lines. As modems became faster and the data send increased collisions became more frequent, leading to corrupted transfers. The CRC-16 was a 16-bit value, so it could only generate 2^16 = 65535 unique values.  </p>
<p>By making the hash longer the chance that two sets of data share the same hash value (a collision) decreases. It is important to realize that this chance will never reach zero! It is entirely (though often unlikely) possible that your program will have two strings that generate the same hash.</p>
<p><strong>Using hashes to store passwords</strong></p>
<p>Hashes are useful as a one-way method to store passwords. In a typical scenario a user types his password and the system generates the hash and compares this with a hash stored on file. </p>
<p>It is not possible to reverse the password from a hash. Thus if someone gets hold of the password file they cannot reverse the original passwords. </p>
<p><strong>Salting the hash</strong></p>
<p>Hashes however are still open to one of the oldest attacks: the dictionary attack. Your system will likely lock out a users after several failed password attempts. If however through a security breach an attacker obtains your hashed password file (or part thereof) it is possible to apply one of many standard dictionaries against the found hashes:</p>
<ol>
<li>Obtain hashed passwords (through online snooping, hacking)</li>
<li>Use dictionary software which contains pre-computed hash values for common passwords</li>
<li>See if the result matches , if so : password found</li>
<li>The hacker can now login and impersonate the user</li>
</ol>
<p>The dictionary attack can be blunted. By adding a unique salt to each hash the attacker needs to re-calculate the dictionary for each users password, greatly increasing the attack time.</p>
<p><em>A salt is a random set of bytes which are added to the data set before calculating the hash. </em></p>
<ol>
<li>User enters password for the first time
<li>The system adds a salt to the password (for example 4 bytes of random data)
<li>The system generates and stores the hash together with the salt
</ol>
<p>When the user returns for another login the system does the following:</p>
<ol>
<li>The users enters the password
<li>The system looks up the stored hash + salt
<li>The system tries if a new hash of the given password + salt matches the stored hash
<li>If they match the user can login
</ol>
<p><strong>A Salted Hash implementation in C#</strong></p>
<p>The following implementation demonstrates how you can implement a Salted Hash in C#. The class defaults to using SHA256Managed hash algorithm, and a salt size of 32 bits. You can however call the class with any other <em>HashAlgorithm</em> derived class (such as for example: <em>SHA1Managed</em>,<em>SHA256Managed</em>, <em>SHA384Managed</em>, <em>SHA512Managed</em> and <em>MD5CryptoServiceProvider</em>) and specify a salt size of any length.</p>
<p>The <em>SaltedHash</em> class provides two routines that do all the leg work:</p>
<p><em>void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)</em></p>
<p>This routine generates the hash and a random salt for a given set of bytes.</p>
<p><em>bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)</em></p>
<p>This routine checks if the data passed, together with the stored salt will generate the same hash as we had earlier calculated.</p>
<p>For convenience two more functions allow us to work with strings directly instead of byte arrays:</p>
<p><em>public void GetHashAndSaltString(string Data, out string Hash, out string Salt)</em></p>
<p>This routine takes a C# hash string and returns both the Hash and Salt as Base-64 encoded string. </p>
<p><em>public bool VerifyHashString(string Data, string Hash, string Salt)</em></p>
<p>The counterpart to the GetHashAndSaltString function, this routine allows us to use verify whether a string returns the same hash with the given salt. </p>
<pre class="brush: c#">
using System;
using System.Security.Cryptography;
using System.Text;

namespace SaltedHash
{
    class SaltedHash
    {
        HashAlgorithm HashProvider;
        int SalthLength;

        /// &lt;summary&gt;
        /// The constructor takes a HashAlgorithm as a parameter.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;HashAlgorithm&quot;&gt;
        /// A &lt;see cref=&quot;HashAlgorithm&quot;/&gt; HashAlgorihm which is derived from HashAlgorithm. C# provides
        /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider
        /// &lt;/param&gt;

        public SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength)
        {
            HashProvider = HashAlgorithm;
            SalthLength = theSaltLength;
        }

        /// &lt;summary&gt;
        /// Default constructor which initialises the SaltedHash with the SHA256Managed algorithm
        /// and a Salt of 4 bytes ( or 4*8 = 32 bits)
        /// &lt;/summary&gt;

        public SaltedHash() : this(new SHA256Managed(), 4)
        {
        }

        /// &lt;summary&gt;
        /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A byte array of the Data to Hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A byte array of the Salt to add to the Hash&lt;/param&gt;
        /// &lt;returns&gt;A byte array with the calculated hash&lt;/returns&gt;

        private byte[] ComputeHash(byte[] Data, byte[] Salt)
        {
            // Allocate memory to store both the Data and Salt together
            byte[] DataAndSalt = new byte[Data.Length + SalthLength];

            // Copy both the data and salt into the new array
            Array.Copy(Data, DataAndSalt, Data.Length);
            Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength);

            // Calculate the hash
            // Compute hash value of our plain text with appended salt.
            return HashProvider.ComputeHash(DataAndSalt);
        }

        /// &lt;summary&gt;
        /// Given a data block this routine returns both a Hash and a Salt
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array containing the data from which to derive the salt
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the hash calculated
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the salt generated
        /// &lt;/param&gt;

        public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)
        {
            // Allocate memory for the salt
            Salt = new byte[SalthLength];

            // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
            // on Unix /dev/urandom
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

            // Create a random salt
            random.GetNonZeroBytes(Salt);

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);
        }

        /// &lt;summary&gt;
        /// The routine provides a wrapper around the GetHashAndSalt function providing conversion
        /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; string containing the data to hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated salt
        /// &lt;/param&gt;

        public void GetHashAndSaltString(string Data, out string Hash, out string Salt)
        {
            byte[] HashOut;
            byte[] SaltOut;

            // Obtain the Hash and Salt for the given string
            GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut);

            // Transform the byte[] to Base-64 encoded strings
            Hash = Convert.ToBase64String(HashOut);
            Salt = Convert.ToBase64String(SaltOut);
        }

        /// &lt;summary&gt;
        /// This routine verifies whether the data generates the same hash as we had stored previously
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;The data to verify &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;The hash we had stored previously&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;The salt we had stored previously&lt;/param&gt;
        /// &lt;returns&gt;True on a succesfull match&lt;/returns&gt;

        public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)
        {
            byte[] NewHash = ComputeHash(Data, Salt);

            //  No easy array comparison in C# -- we do the legwork
            if (NewHash.Length != Hash.Length) return false;

            for (int Lp = 0; Lp &lt; Hash.Length; Lp++ )
                if (!Hash[Lp].Equals(NewHash[Lp]))
                    return false;

            return true;
        }

        /// &lt;summary&gt;
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A UTF-8 encoded string containing the data to verify&lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;A base-64 encoded string containing the previously stored hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A base-64 encoded string containing the previously stored salt&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        public bool VerifyHashString(string Data, string Hash, string Salt)
        {
            byte[] HashToVerify = Convert.FromBase64String(Hash);
            byte[] SaltToVerify = Convert.FromBase64String(Salt);
            byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
            return VerifyHash(DataToVerify, HashToVerify, SaltToVerify);
        }

    }

    /// &lt;summary&gt;
    /// This little demo code shows how to encode a users password.
    /// &lt;/summary&gt;

    class SaltedHashDemo
    {
        public static void Main(string[] args)
        {
            // We use the default SHA-256 &amp; 4 byte length
            SaltedHash demo = new SaltedHash();

            // We have a password, which will generate a Hash and Salt
            string Password = &quot;MyGlook234&quot;;
            string Hash;
            string Salt;

            demo.GetHashAndSaltString(Password, out Hash, out Salt);
            Console.WriteLine(&quot;Password = {0} , Hash = {1} , Salt = {2}&quot;, Password, Hash, Salt);

            // Password validation
            //
            // We need to pass both the earlier calculated Hash and Salt (we need to store this somewhere safe between sessions)

            // First check if a wrong password passes
            string WrongPassword = &quot;OopsOops&quot;;
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, WrongPassword, demo.VerifyHashString(WrongPassword, Hash, Salt));

            // Check if the correct password passes
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, Password, demo.VerifyHashString(Password, Hash, Salt));

        }
    }

}
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/fernando/">Looking Glass</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
