<?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; generics</title>
	<atom:link href="http://www.dijksterhuis.org/tag/generics/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>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>Generics in C#</title>
		<link>http://www.dijksterhuis.org/generics-in-c/</link>
		<comments>http://www.dijksterhuis.org/generics-in-c/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 08:29:22 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=116</guid>
		<description><![CDATA[
You heard might have heard about generics, but how do they work in C# ? And what is that &#60;T&#62; doing in the class definition? This article shows you the benefits of using generics, and how to implement them yourself.


Version 2 of C# introduced something called a &#8220;generic&#8221;. In this article we will look into [...]<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/11/codereuse.jpg" alt="" title="Code Re-Use in C# through Generics" width="500" height="311" class="alignnone size-full wp-image-123" /><br />
<em>You heard might have heard about generics, but how do they work in C# ? And what is that &lt;T&gt; doing in the class definition? This article shows you the benefits of using generics, and how to implement them yourself.<br />
</em><br />
<span id="more-116"></span></p>
<p>Version 2 of C# introduced something called a &#8220;generic&#8221;. In this article we will look into what a generic is, and why you would want to use them. Generics are similar to a concept frequently used in C++ Templates. They allow you to better re-use your code while at the same time providing more information to the compiler on what should be allowed, and what shouldn&#8217;t.</p>
<p>The code below give an example on how  generics can improve the compilers knowledge of what it should accept. A very basic vector array class is defined to accept only strings.</p>
<p><em>This code is just for illustration of the Generics concept. Normally you would just use the build in C# Array type to obtain the same Array functionality. </em></p>
<pre class="brush: c#">
    class Vector
    {
        string[] elements;

        public Vector(int maximum_elements)
        {
            elements = new string[maximum_elements];
        }

        public string this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            Vector test = new Vector(20);

            test[1] = &quot;42&quot;;
            // The compiler catches this, we cannot convert an integer to string
            // test[2] = 123;
            string theAnswer = test[1];
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>The above vector array code can only be used for storing strings,limiting our re-use of the code. What to do if we would like to store integers instead?</p>
<p>We can improve the code by making it more abstract by replacing the <em>int</em> definitions with the more general <em>object</em> tag. </p>
<p> It is now possible to store all kinds of elements (not just integers) in the Vector. But because the compiler no longer knows what type is stored in the Vector, it allows all kinds. Worse, we now need to cast all return values to our main type (<em>string</em>) as the compiler cannot implicitly convert objects to strings. </p>
<pre class="brush: c#">
    class Vector
    {
        object[] elements;

        public Vector(int maximum_elements)
        {
            elements = new object[maximum_elements];
        }

        public object this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            Vector test = new Vector(20);

            test[1] = &quot;42&quot;; // The Vector doesn&#039;t know about our type
            test[2] = 123;// So both strings and numbers are OK, allowing for mistakes
            string theAnswer = (string) test[1];// We are also forced to cast (object) to (string)
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>Generics help out by allowing us to define our Vector as an abstract type. Note the &lt;T&gt; given in the class definition of the Vector. It replaces all instances where we would have said &#8220;string&#8221;, &#8220;int&#8221; or &#8220;object&#8221; previously.</p>
<pre class="brush: c#">
    class Vector&lt;T&gt;
    {
        T[] elements;

        public Vector(int maximum_elements)
        {
            elements = new T[maximum_elements];
        }

        public T this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass

    {
        public static void Main(string[] args)
        {
            Vector&lt;string&gt; test= new Vector&lt;string&gt;(20);

            test[1] = &quot;42&quot;;
            // The compiler catches this, we cannot convert an integer to string
            // test[2] = 123;
            string theAnswer = test[1];
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>The above example removes the need to typecast any returned value, the compiler is already aware of the correct type (&#8221;string&#8221; in our example). The code is also type-safe as it is no longer possible to assign the wrong type to an element in the Vector and finally, the above Vector code can be re-used to hold any kind of variable.</p>
<p>We could re-use the final code to create any kind of container; suitable for holding only a single type.</p>
<pre class="brush: c#">
Vector&lt;int&gt;    test1 = new Vector&lt;int&gt;(20);
Vector&lt;string&gt; test2 = new Vector&lt;string&gt;(20);
Vector&lt;float&gt;  test3 = new Vector&lt;float&gt;(20);
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/9229859@N02/">bucklava</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/generics-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
