<?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>Coffee, Code and Chocolate &#187; Microsoft</title>
	<atom:link href="http://blog.ganeshzone.net/blog/index.php/category/microsoft/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ganeshzone.net/blog</link>
	<description>throw new Exception(&#34;#fail&#34;);</description>
	<lastBuildDate>Mon, 26 Jul 2010 19:45:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>My first look at the dynamic keyword in C# 4.0</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 20:17:59 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[dynamic typing]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1023</guid>
		<description><![CDATA[<p style="text-align: justify;">I have always believed that strong typing is the holy grail of .NET, which is not to be messed with, and it has been my primary grouse with VB.NET is that it uses sneaky workarounds to circumvent the typing rules of the CLR. C# for most of its initial existence followed static typing [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I have always believed that strong typing is the holy grail of .NET, which is not to be messed with, and it has been my primary grouse with VB.NET is that it uses sneaky workarounds to circumvent the typing rules of the CLR. C# for most of its initial existence followed static typing religiously with slight changes being seen in 3.0 with the var keyword. But in 4.0, everything changed with the introduction of the Dynamic Language Runtime (DLR).</p>
<p style="text-align: justify;">The DLR according to wikipedia is <em><strong>&#8220;an ongoing effort to bring a set of services that run on top of the Common Language Runtime (CLR) and provides language services for several different dynamic languages.&#8221;</strong></em> As the definition says, it is independent of the CLR and adds no new OpCodes to the IL. Languages like C# used the DLR to introduce dynamic typing while maintaining the existing mechanism of statically determining types.</p>
<p style="text-align: justify;">The dynamic keyword is the C# construct introduced for this. In short &#8211; it tells the compiler that the call to this method is to be resolved at runtime and not to be bothered by throwing compiler errors. Lets see a simple example for the usage of the dynamic keyword. Suppose you have a book class which has four main properties &#8211; Author, Publisher, Price and Number Of Pages. However, each book may have a lot of other properties as well, which you wont know at design time. So the question arises, how to store the additional information? The first answer that would come to mind is storing them in a collection class and later retrieving it. The dynamic class provides you with a neat way of doing this shown in the code below :-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// The dynamic keyword bypasses any compile time checking for this object</span>
            dynamic _daVinciCode <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Book<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Sample Author&quot;</span>, <span style="color: #666666;">&quot;SomePublisher&quot;</span>, <span style="color: #FF0000;">250</span>, <span style="color: #FF0000;">450</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">/*** EXTRA PROPERTIES - NOT PRESENT IN THE OBJECT***/</span>
            _daVinciCode.<span style="color: #0000FF;">BookStores</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;Landmark&quot;</span>, <span style="color: #666666;">&quot;Oddyssey&quot;</span>, <span style="color: #666666;">&quot;Crosswords&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
            _daVinciCode.<span style="color: #0000FF;">CitiesAvailable</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;Delhi&quot;</span>, <span style="color: #666666;">&quot;Bangalore&quot;</span>, <span style="color: #666666;">&quot;Chennai&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
            _daVinciCode.<span style="color: #0000FF;">ExtraVat</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">45</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">/*** PRINTING OUT EXTRA PROPERTIES VALUE ***/</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>_daVinciCode.<span style="color: #0000FF;">ExtraVat</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// This is our dynamic class. It defines 4 concrete properties</span>
    <span style="color: #008080; font-style: italic;">/// and a dictionary class for storing any other property values</span>
    <span style="color: #008080; font-style: italic;">/// as well. The abstract class DynamicObject is implemented</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Book<span style="color: #008000;">:</span>DynamicObject
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Our four defined properties</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Author <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Publisher <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">double</span> Price <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> NumberOfPages <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Constructor - Parametrized</span>
        <span style="color: #0600FF;">public</span> Book<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _author, <span style="color: #FF0000;">string</span> _publisher, <span style="color: #FF0000;">double</span> _price, <span style="color: #FF0000;">int</span> _numberOfPages<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Author</span> <span style="color: #008000;">=</span> _author<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Publisher</span> <span style="color: #008000;">=</span> _publisher<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Price</span> <span style="color: #008000;">=</span> _price<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">NumberOfPages</span> <span style="color: #008000;">=</span> _numberOfPages<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//This collection object stores all the extra properties</span>
        <span style="color: #0600FF;">public</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> _extraProperties <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//At runtime this method is called in order to bind the propertyname to a Getter</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">bool</span> TryGetMember<span style="color: #000000;">&#40;</span>GetMemberBinder binder, <span style="color: #0600FF;">out</span> <span style="color: #FF0000;">object</span> result<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> _extraProperties.<span style="color: #0000FF;">TryGetValue</span><span style="color: #000000;">&#40;</span>binder.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">out</span> result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//At runtime this method is called in order to bind the propertyname to a setter</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">bool</span> TrySetMember<span style="color: #000000;">&#40;</span>SetMemberBinder binder, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _extraProperties.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>binder.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The Book class is a dynamic type and derives from the abstract class DynamicObject. This base class can help determine how binding should occur at runtime. In our example, the dictionary object stores all the additional properties of the book class. The two overriden methods TryGetMember and the TrySetMember are responsible for the binding of the new properties to the dictionary object. The first time a property on a dynamic type is encountered, the DLR binds the property and then caches its address. So any subsequent calls are faster.</p>
<p>More on the DLR in future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generic Binary Search Tree in C# .NET</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 13:33:19 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Data structures]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=895</guid>
		<description><![CDATA[<p style="text-align: justify;">Binary Trees are tree type data structures that contain two child nodes. They can be used to implement Binary Search trees, structures where the left child has a value lesser than the node and the right child has a greater value. Usually Linear collection objects require iteration linearly over the list. In the [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Binary Trees are tree type data structures that contain two child nodes. They can be used to implement Binary Search trees, structures where the left child has a value lesser than the node and the right child has a greater value. Usually Linear collection objects require iteration linearly over the list. In the worst case scenario that the element to be searched is at the end of the list this can take a really really long time. For Binary Trees the search time is cut by half. Since every node tells the search which direction to go and search.</p>
<p style="text-align: justify;">I implemented a basic Binary Tree in .NET for adding custom types. The Tree is generic and can be used to add any type objects. Also the object must implement the generic versions of IComparable and IEquitable for their types and object types. This leaves the search logic&#8217;s implementation to the type rather than the data structure. The complete solution can be downloaded <a href="http://www.ganeshzone.net/Files/BinaryTry.zip">here</a>.</p>
<p>Lets see the declaration of the Binary Tree along with the private members.</p>
<pre class="code"><span style="color: blue;">class </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; <span style="color: blue;">where
    </span>T:<span style="color: #2b91af;">IComparable</span>&lt;T&gt;,
    <span style="color: #2b91af;">IEquatable</span>&lt;T&gt;,
    <span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: blue;">object</span>&gt;,
    <span style="color: #2b91af;">IComparable</span>&lt;<span style="color: blue;">object</span>&gt;
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _parentNode;
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _leftNode;
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _rightNode;
    <span style="color: blue;">public </span>T Value { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<p style="text-align: justify;">Each BinaryTree object must be aware of its parent node and its left and right children, and the value it holds.  Lets see the logic for adding the node. The adding logic is recursive. If it finds a null value, then the value is substituted. If not, then the node to be added is compared. If the value is lesser than the same method is called on the leftnode. This happens recursively till we get the node where the value is to be added.</p>
<pre class="code"><span style="color: blue;">public void </span>AddNode(T _nodeTobeAdded)
{
    <span style="color: blue;">if </span>(<span style="color: blue;">null</span>==Value)
        <span style="color: green;">//We found the value. Yay!!
        </span><span style="color: blue;">this</span>.Value = _nodeTobeAdded;
    <span style="color: blue;">else
    </span>{
        <span style="color: green;">//Compare the node to be added. Here the
        //type's IComparable is called.
        </span><span style="color: blue;">if </span>(_nodeTobeAdded.CompareTo(Value) &lt; 0)
        {
            <span style="color: green;">//Go down the left node. If the left node is null,
            //then create a new object, else return the existing object.
            </span>_leftNode = <span style="color: blue;">null</span>==_leftNode ?<span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;(<span style="color: blue;">this</span>):_leftNode;
            _leftNode.AddNode(_nodeTobeAdded);
        }
        <span style="color: blue;">else
        </span>{
            <span style="color: green;">//Go Down the right node.
            </span>_rightNode = <span style="color: blue;">null</span>==_rightNode?<span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;(<span style="color: blue;">this</span>):_rightNode;
            _rightNode.AddNode(_nodeTobeAdded);
        }
    }
}</pre>
<p style="text-align: justify;">The GetNode method follows a similar logic, with recursive searching of the tree till a match is found, if no match is found then a null value is returned. Note that only around half of the tree is searched, rather than all of the nodes, as would be the case with a linkedList. GetNode is implemented both for the type and an object. In both cases the Equals method&#8217;s implementation is called, giving the generic type the ability to decide on its own equality logic.</p>
<pre class="code"><span style="color: blue;">public </span>T GetNode(T _nodeToBeGotten)
{
   <span style="color: blue;">if</span>(_nodeToBeGotten.Equals(Value))
       <span style="color: blue;">return </span>Value;
   <span style="color: blue;">else if</span>(_nodeToBeGotten.CompareTo(Value)&lt;0)
       <span style="color: blue;">return null</span>==_leftNode? <span style="color: blue;">default</span>(T): _leftNode.GetNode(_nodeToBeGotten);
   <span style="color: blue;">else
       return null</span>==_rightNode?<span style="color: blue;">default</span>(T): _rightNode.GetNode(_nodeToBeGotten);
}

<span style="color: blue;">public </span>T GetNode(<span style="color: blue;">object </span>o)
{
    <span style="color: blue;">if </span>(Value.Equals(o))
        <span style="color: blue;">return </span>Value;
    <span style="color: blue;">else if </span>(Value.CompareTo(o)&gt;0)
        <span style="color: blue;">return </span>(<span style="color: blue;">null </span>== _leftNode) ?
            <span style="color: blue;">default</span>(T) : _leftNode.GetNode(o);
    <span style="color: blue;">else
        return null </span>== _rightNode ?
            <span style="color: blue;">default</span>(T) : _rightNode.GetNode(o);
}</pre>
<p>Deleting is a bit tricky business. We have four scenarios here:-</p>
<ol>
<li style="text-align: justify;"> Its a leaf node, i.e. both the left and right children are null. This is the simplest scenario. Simply set the node itself to null</li>
<li style="text-align: justify;">The LeftNode is null but the right node is not, in this scenario &#8211; the node&#8217;s right node is set to the parent node&#8217;s right node, and the node is set to null.</li>
<li style="text-align: justify;">The Right node is null but left node is not. It is handled similar to the previous scenario.</li>
<li style="text-align: justify;">Both leftNode and rightNode is not null. In this scenarios we need to go down the leftnode, and iterate to its right most non empty node. This node is to be replaced with the node to be deleted. Just the value needs to be replaced and the right most node should be orphaned.</li>
</ol>
<pre class="code"><span style="color: blue;">public void </span>DeleteNode(<span style="color: blue;">object </span>o)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1 = <span style="color: blue;">this</span>.GetTreeNode(o);
    DeleteNode(_tempNode1);
}

<span style="color: blue;">public void </span>DeleteNode(T _nodeTobeDeleted)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1 = <span style="color: blue;">this</span>.GetTreeNode(_nodeTobeDeleted);
    DeleteNode(_tempNode1);
}

<span style="color: blue;">private void </span>DeleteNode(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode2 = _tempNode1;
    <span style="color: blue;">if </span>((<span style="color: blue;">null </span>== _tempNode1._leftNode) &amp;&amp; (<span style="color: blue;">null </span>== _tempNode1._rightNode))
        _tempNode1._parentNode = <span style="color: blue;">null</span>;
    <span style="color: blue;">else if </span>(<span style="color: blue;">null </span>== _tempNode1._leftNode)
        _tempNode1._parentNode._rightNode = _tempNode1._rightNode;
    <span style="color: blue;">else if </span>(<span style="color: blue;">null </span>== _tempNode1._rightNode)
        _tempNode1._parentNode._leftNode = _tempNode1._leftNode;
    <span style="color: blue;">else
    </span>{
        <span style="color: blue;">bool </span>_goingRight = <span style="color: blue;">false</span>;
        _tempNode1 = _tempNode1._leftNode;
        <span style="color: blue;">while </span>(_tempNode1._rightNode != <span style="color: blue;">null</span>)
        {
            _tempNode1 = _tempNode1._rightNode;
            _goingRight = <span style="color: blue;">true</span>;
        }
        _tempNode2.Value = _tempNode1.Value;
        <span style="color: blue;">if </span>(_goingRight) _tempNode1._parentNode._rightNode = <span style="color: blue;">null</span>;
        <span style="color: blue;">else </span>_tempNode1._parentNode._leftNode = <span style="color: blue;">null</span>;
        _tempNode1 = <span style="color: blue;">null</span>;
    }
}

<span style="color: green;">//Private methods to get the nodes to be deleted
</span><span style="color: blue;">private </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; GetTreeNode(T _nodeToBeGotten)
{
    <span style="color: blue;">if </span>(_nodeToBeGotten.Equals(Value))
        <span style="color: blue;">return this</span>;
    <span style="color: blue;">else if </span>(_nodeToBeGotten.CompareTo(Value) &lt; 0)
        <span style="color: blue;">return null </span>== _leftNode ? <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _leftNode.GetTreeNode(_nodeToBeGotten);
    <span style="color: blue;">else
        return null </span>== _rightNode ? <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _rightNode.GetTreeNode(_nodeToBeGotten);
}

<span style="color: blue;">private </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; GetTreeNode(<span style="color: blue;">object </span>o)
{
    <span style="color: blue;">if </span>(Value.Equals(o))
        <span style="color: blue;">return this</span>;
    <span style="color: blue;">else if </span>(Value.CompareTo(o) &gt; 0)
        <span style="color: blue;">return </span>(<span style="color: blue;">null </span>== _leftNode) ?
            <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _leftNode.GetTreeNode(o);
    <span style="color: blue;">else
        return null </span>== _rightNode ?
            <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _rightNode.GetTreeNode(o);
}</pre>
<p>The class which could be added to the tree needs to implement the four interfaces i mentioned. I implemented an Employee class which has just two fields Name and age and the comparison is done based on the age.</p>
<pre class="code"><span style="color: blue;">class </span><span style="color: #2b91af;">Employee </span>: <span style="color: #2b91af;">IComparable</span>&lt;<span style="color: #2b91af;">Employee</span>&gt;,<span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: #2b91af;">Employee</span>&gt;,<span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: blue;">object</span>&gt;,<span style="color: #2b91af;">IComparable</span>&lt;<span style="color: blue;">object</span>&gt;
    {
        <span style="color: blue;">private string </span>_name;
        <span style="color: blue;">private int </span>_age;

        <span style="color: blue;">public int </span>Age{<span style="color: blue;">get</span>{<span style="color: blue;">return </span>_age;}}

        <span style="color: blue;">public </span>Employee(<span style="color: blue;">string </span>_name, <span style="color: blue;">int </span>_age)
        {
            <span style="color: blue;">this</span>._name = _name;
            <span style="color: blue;">this</span>._age = _age;
        }

        <span style="color: blue;">#region </span>IComparable&lt;Employee&gt; Members

        <span style="color: blue;">public int </span>CompareTo(<span style="color: #2b91af;">Employee </span>other)
        {
            <span style="color: blue;">if </span>(<span style="color: blue;">this</span>._age &lt; other._age)
                <span style="color: blue;">return </span>-1;
            <span style="color: blue;">else
                return </span>1;
        }

        <span style="color: blue;">#endregion

        public bool </span>Equals(<span style="color: #2b91af;">Employee </span>other)
        {
            <span style="color: blue;">if </span>(<span style="color: blue;">this</span>._age == other._age)
                <span style="color: blue;">return true</span>;
            <span style="color: blue;">else
                return false</span>;
        }

        <span style="color: blue;">#region </span>IEquatable&lt;object&gt; Members

        <span style="color: blue;">public override bool </span>Equals(<span style="color: blue;">object </span>other)
        {
            <span style="color: blue;">int </span>_age=0;
            <span style="color: blue;">if </span>(<span style="color: blue;">int</span>.TryParse(other.ToString(), <span style="color: blue;">out </span>_age))
            {
                <span style="color: blue;">return this</span>._age == _age ? <span style="color: blue;">true </span>: <span style="color: blue;">false</span>;
            }
            <span style="color: blue;">else return false</span>;
        }

        <span style="color: blue;">#endregion

        #region </span>IComparable&lt;object&gt; Members

        <span style="color: blue;">public int </span>CompareTo(<span style="color: blue;">object </span>other)
        {
            <span style="color: blue;">int </span>_age = 0;
            <span style="color: blue;">if </span>(<span style="color: blue;">int</span>.TryParse(other.ToString(), <span style="color: blue;">out </span>_age))
                <span style="color: blue;">return this</span>._age &lt; _age ? -1 : 1;
            <span style="color: blue;">else return </span>1;
        }

        <span style="color: blue;">#endregion

    </span>}</pre>
<p>This is the main method which adds a few objects to the tree collection.</p>
<pre class="code"><span style="color: blue;">static void </span>Main(<span style="color: blue;">string</span>[] args)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;Employee&gt; _btree = <span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;Employee&gt;(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"RootValue"</span>,40));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test1"</span>, 34));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test2"</span>, 26));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test3"</span>, 65));
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tic-Tac-Toe game in Silverlight</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 20:05:12 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=852</guid>
		<description><![CDATA[<p>Recently someone asked me to write a TicTacToe game. So I worked out a rough logic for it. Heres the code. The idea is that the computer first scans through the tic-tac-toe board for any winning positions available. If none are available, then it looks for the manual user&#8217;s winning positions. If its able to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently someone asked me to write a TicTacToe game. So I worked out a rough logic for it. Heres the code. The idea is that the computer first scans through the tic-tac-toe board for any winning positions available. If none are available, then it looks for the manual user&#8217;s winning positions. If its able to find them, it blocks it. If not the next available position is filled. The game can be played by clicking any of the squares below.</p>
<div style="text-align:center">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="340"><param name="source" value="http://www.ganeshzone.net/Silverlight/Objects/TicTacToe.xap"/><param name="onError" value="onSilverlightError" /><param name="background" value="white" /><param name="minRuntimeVersion" value="3.0.40818.0" /><param name="autoUpgrade" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=149156&#038;v=3.0.40818.0" style="text-decoration:none"><br />
 			  <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/></p>
<p>		  </a><br />
	    </object> </div>
<p>Here is the code for the game as a silverlight application. The complete project can be downloaded <a href="http://www.ganeshzone.net/Files/TicTacToe.zip">here</a>.</p>
<p>The XAML is quite simple. Just a grid with three rows and three columns</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;gridGame&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;grid</span> .RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;grid</span> .ColumnDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>It is then filled with the buttons in the Code Behind. I have hardcoded the grid size of three but this will work with any size.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF;">public</span> MainPage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            InitializeComponent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _fromConstructor<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_fromConstructor<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                gridGame.<span style="color: #0000FF;">Children</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            _logic <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TicTacLogic<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> j <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> j <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span> j<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    Button _btnGrid <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Button<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;btn&quot;</span> <span style="color: #008000;">+</span> i.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> j.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    gridGame.<span style="color: #0000FF;">Children</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_btnGrid<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    Grid.<span style="color: #0000FF;">SetRow</span><span style="color: #000000;">&#40;</span>_btnGrid, j<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    Grid.<span style="color: #0000FF;">SetColumn</span><span style="color: #000000;">&#40;</span>_btnGrid, i<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Height</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">80</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">80</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Click</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> RoutedEventHandler<span style="color: #000000;">&#40;</span>_btnGrid_Click<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            _logic.<span style="color: #0000FF;">StartGame</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>All the dynamically generated buttons have a single event handler. The idea is to identify the button which sent the event from the name. Once we have the position of the button, the content has to be changed with an X. After the user marks, the computer does its stuff and makes its move. After every marking, a check is done if someone has won or the board is full.</p>
</pre>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">void</span> _btnGrid_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, RoutedEventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Button _userClicked <span style="color: #008000;">=</span> sender <span style="color: #0600FF;">as</span> Button<span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _xPos <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>_userClicked.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span>,<span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>_userClicked.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span>,<span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _userClicked.<span style="color: #0000FF;">Content</span> <span style="color: #008000;">=</span> GetMarking<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;X&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _logic.<span style="color: #0000FF;">ClickUser</span><span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #000000;">&#40;</span>_logic.<span style="color: #0000FF;">CheckIfSomeoneWon</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> _logic.<span style="color: #0000FF;">CheckIfBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">int</span> _xCom <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                <span style="color: #FF0000;">int</span> _yCom <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                _logic.<span style="color: #0000FF;">MoveComputer</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _xCom, <span style="color: #0600FF;">ref</span> _yCom<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>UIElement _tempElem <span style="color: #0600FF;">in</span> gridGame.<span style="color: #0000FF;">Children</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    Button _comBtn <span style="color: #008000;">=</span> _tempElem <span style="color: #0600FF;">as</span> Button<span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_comBtn <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> _comBtn.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;btn&quot;</span> <span style="color: #008000;">+</span> _xCom <span style="color: #008000;">+</span> _yCom<span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        _comBtn.<span style="color: #0000FF;">Content</span> <span style="color: #008000;">=</span> GetMarking<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;O&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                        break<span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_logic.<span style="color: #0000FF;">CheckIfSomeoneWon</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> _logic.<span style="color: #0000FF;">CheckIfBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span>
                InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> TextBlock GetMarking<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _mark<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            TextBlock _t <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TextBlock<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> _mark<span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">FontSize</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">25</span><span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">FontWeight</span> <span style="color: #008000;">=</span> FontWeights.<span style="color: #0000FF;">Bold</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> _t<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The Board class maintains two important things. The position of all the squares and which player has it marked. The Board doesnt depend on the Player objects. It has an object of the WinningPositions object which calculates the winning positions which can be compared with later. This object makes it possible to play  with larger grids.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Board
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">readonly</span> <span style="color: #FF0000;">int</span> MAXSIZE<span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>positionmarking<span style="color: #008000;">&gt;</span> _boardState <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>positionmarking<span style="color: #008000;">&gt;&lt;</span>positionmarking<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> _allWinningPositions<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>positionmarking<span style="color: #008000;">&gt;</span> BoardState <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _boardState<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> AllWinningPositions <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _allWinningPositions<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> MaxSize <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> MAXSIZE<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Board<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">MAXSIZE</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Board<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _maxSize<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        MAXSIZE <span style="color: #008000;">=</span> _maxSize<span style="color: #008000;">;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _allWinningPositions <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> WinningPositions<span style="color: #000000;">&#40;</span>MAXSIZE<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xPos<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>_xPos<span style="color: #008000;">&lt;</span>maxsize <span style="color: #008000;">;</span>_xPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _yPos <span style="color: #008000;">&lt;</span> MAXSIZE<span style="color: #008000;">;</span> _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _boardState.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> PositionMarking<span style="color: #000000;">&#40;</span>_xPos,_yPos<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> MarkPosition<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xUser, <span style="color: #FF0000;">int</span> _yUser, <span style="color: #FF0000;">bool</span> _userMarked<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempPos <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempPos.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">==</span> _xUser <span style="color: #008000;">&amp;&amp;</span> _tempPos.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">==</span> _yUser<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _tempPos.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_userMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
<span style="color: #008080;">#if DEBUG</span>
        PrintBoardState<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> MarkedByUser<span style="color: #000000;">&#40;</span>Position _tempPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempPos.<span style="color: #0000FF;">X</span> <span style="color: #008000;">==</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">&amp;&amp;</span> _tempPos.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">==</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> _tempMark.<span style="color: #0000FF;">IsUserMarked</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Position Not found on Board&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#if DEBUG</span>
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> PrintBoardState<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">string</span> _userMarked <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">string</span> _compMarked <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                _userMarked <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot;(&quot;</span><span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;) &quot;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>
                _compMarked <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot;(&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;) &quot;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;USER: &quot;</span> <span style="color: #008000;">+</span> _userMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;COMP: &quot;</span> <span style="color: #008000;">+</span> _compMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;________________________________________&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #008080;">#endif</span>
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> IsBoardFull<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Board Full&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The Winning Position class is given below and all positions are calculated at initialization. First the horizontal ones are considered and then the vertical ones. The remaining diagonal positons are taken care later. Each winning position is stored in an array of the position object which just holds the value of the Squares. These arrays are stored in a generic List.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> WinningPositions
<span style="color: #000000;">&#123;</span>
    List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> _allWinningPositions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos1<span style="color: #008000;">;</span>
    Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos2<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> AllWinningPositions
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _allWinningPositions<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> WinningPositions<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _maxSize<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _winPos1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_maxSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        _winPos2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_maxSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        PopulateWinningPositions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> PopulateWinningPositions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> _iCounter<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> _xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _xPos <span style="color: #008000;">&lt;</span> _winPos2.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _yPos <span style="color: #008000;">&lt;</span> _winPos2.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _winPos1<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _winPos2<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_yPos, _xPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _iCounter<span style="color: #008000;">++;</span>
            <span style="color: #000000;">&#125;</span>
            _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos2<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _winPos1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_winPos1.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            _winPos2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_winPos2.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>, _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>_xPos <span style="color: #008000;">&lt;</span> _winPos1.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span>, _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _winPos1<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _iCounter<span style="color: #008000;">++;</span>
        <span style="color: #000000;">&#125;</span>
        _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>, _yPos <span style="color: #008000;">=</span> _winPos1.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> _xPos <span style="color: #008000;">&lt;</span> _winPos1.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span>, _yPos<span style="color: #008000;">--</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _winPos2<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _iCounter<span style="color: #008000;">++;</span>
        <span style="color: #000000;">&#125;</span>
        _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos2<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Then there is the Player class of which we create two objects. The user takes care of his own moving logic, all we need to do is to change the state of the square for him. But the computer has its method called the <strong>SmartMove</strong>. Here we first move through the winning positions to identify any open squares that can be marked. If there are no squares, then we look to block the opponent's winning. If even this opportunity is not found, we mark an available open square.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Player
<span style="color: #000000;">&#123;</span>
    Board _currentBoardPosition<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span> _isComputer<span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>position<span style="color: #008000;">&gt;</span> _allMarkedPositions<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Player<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _isComputer,Board _currentBoardPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>._isComputer <span style="color: #008000;">=</span> _isComputer<span style="color: #008000;">;</span>
        _allMarkedPositions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _currentBoardPosition <span style="color: #008000;">=</span> _currentBoardPos<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> SmartMove<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _xCom, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _yCom<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">bool</span> _markingDone <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">bool</span> _blockUser <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        Position _userBlock <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos <span style="color: #0600FF;">in</span> _currentBoardPosition.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> _userMarked <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _computerMarked <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _nullMarked<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
            Position _openPos<span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position _tempPos <span style="color: #0600FF;">in</span> _winPos<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> isUserMarked <span style="color: #008000;">=</span> _currentBoardPosition.<span style="color: #0000FF;">MarkedByUser</span><span style="color: #000000;">&#40;</span>_tempPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked<span style="color: #008000;">==</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                    _userMarked<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>
                    _computerMarked<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span>
                <span style="color: #000000;">&#123;</span>
                    _openPos <span style="color: #008000;">=</span> _tempPos<span style="color: #008000;">;</span>
                    _nullMarked<span style="color: #008000;">++;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_computerMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">&amp;&amp;</span> _nullMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Wining block: &quot;</span> <span style="color: #008000;">+</span> _openPos.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _openPos.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_openPos.<span style="color: #0000FF;">X</span>, _openPos.<span style="color: #0000FF;">Y</span>, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _xCom <span style="color: #008000;">=</span> _openPos.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
                _yCom <span style="color: #008000;">=</span> _openPos.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
                _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_userMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">&amp;&amp;</span> _nullMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _userBlock <span style="color: #008000;">=</span> _openPos<span style="color: #008000;">;</span>
                _blockUser <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_blockUser <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>_markingDone<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_userBlock.<span style="color: #0000FF;">X</span>, _userBlock.<span style="color: #0000FF;">Y</span>, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _xCom <span style="color: #008000;">=</span> _userBlock.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
            _yCom <span style="color: #008000;">=</span> _userBlock.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
            _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_markingDone<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//No Winning Position Found or not able to block;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _posMark <span style="color: #0600FF;">in</span> _currentBoardPosition.<span style="color: #0000FF;">BoardState</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_posMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                    _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span>, _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span>,<span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _xCom <span style="color: #008000;">=</span> _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
                    _yCom <span style="color: #008000;">=</span> _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;</span></pre></td></tr></table></div>

<p>Since the Board needs to maintain the state of each and every position on itself, we have another object for it, which maintains a position object and a nullable boolean. If the boolean is true, then the square is marked by the user, if false - then by the computer. If its still null - its open and can be marked. The marking is done by the object's method which makes a check to make sure no players marking is overwritten by another.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PositionMarking
<span style="color: #000000;">&#123;</span>
    Position _boardPos<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> _isUserMarked<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position BoardPosition <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _boardPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> IsUserMarked <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _isUserMarked<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> PositionMarking<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xPos,<span style="color: #FF0000;">int</span> _yPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _isUserMarked <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
        _boardPos <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> MarkPosition<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _markedByUser<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>_isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        _isUserMarked <span style="color: #008000;">=</span> _markedByUser<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">else</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Position already taken&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Then there is the rest of the code including our business logic layer.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> TicTacLogic
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">bool</span> _userToMove<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span> _resultHasCome<span style="color: #008000;">;</span>
    Player _user<span style="color: #008000;">;</span>
    Player _computer<span style="color: #008000;">;</span>
    Board _gameBoard<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> TicTacLogic<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _userToMove <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
        _resultHasCome <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> StartGame<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> ClickUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xUser, <span style="color: #FF0000;">int</span> _yUser<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> _gameBoard.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_xUser, _yUser, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> MoveComputer<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _xCom, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _yCom<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _computer.<span style="color: #0000FF;">SmartMove</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _xCom, <span style="color: #0600FF;">ref</span> _yCom<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _gameBoard <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Board<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _user <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Player<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span>,_gameBoard<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _computer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Player<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span>,_gameBoard<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> CheckIfSomeoneWon<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _tempWin <span style="color: #0600FF;">in</span> _gameBoard.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> _userWon<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _compWon<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position _p <span style="color: #0600FF;">in</span> _tempWin<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> isUserMarked <span style="color: #008000;">=</span> _gameBoard.<span style="color: #0000FF;">MarkedByUser</span><span style="color: #000000;">&#40;</span>_p<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                    _userWon<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span>
                    _compWon<span style="color: #008000;">++;</span>
&nbsp;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_userWon <span style="color: #008000;">==</span> _gameBoard.<span style="color: #0000FF;">MaxSize</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;User Won&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_compWon <span style="color: #008000;">==</span> _gameBoard.<span style="color: #0000FF;">MaxSize</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Computer Won&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> CheckIfBoardFull<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> _gameBoard.<span style="color: #0000FF;">IsBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Position
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _xPos<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">int</span> _yPos<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> X <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _xPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Y <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _yPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> xPos, <span style="color: #FF0000;">int</span> yPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>._xPos <span style="color: #008000;">=</span> xPos<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._yPos <span style="color: #008000;">=</span> yPos<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

</position></pre>
<p></maxsize></position></positionmarking></position></positionmarking></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying ASP.NET MVC Apps on Shared Hosting</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 18:20:39 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=823</guid>
		<description><![CDATA[<p>Here are the steps to deploy MVC applications to servers with shared hosting providers.</p>

In your Hosting provider&#8217;s IIS management panel, create a sub directory and configure it as an appplication- root, so that it is recognized as an asp.net application.


Set your MVC dll&#8217;s Copy To Local property to true, so that they are copied to [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the steps to deploy MVC applications to servers with shared hosting providers.</p>
<ul>
<li>In your Hosting provider&#8217;s IIS management panel, create a sub directory and configure it as an appplication- root, so that it is recognized as an asp.net application.</li>
</ul>
<ul>
<li>Set your MVC dll&#8217;s Copy To Local property to true, so that they are copied to the bin directory of the project.</li>
</ul>
<ul>
<li>Edit your web.config file and update the debug property to false. This holds true for all web applications.</li>
</ul>
<ul>
<li>Update the connection strings to your hosting provider&#8217;s connection strings.</li>
</ul>
<p>Thats it. Your MVC application should run fine. Mine <a href="http://ganeshzone.net/mvctestdeploy/">does</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>ASP.NET Evolution: WebForms v/s MVC</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 05:43:42 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=789</guid>
		<description><![CDATA[<p style="text-align: justify;">Though MVC is an age old architectural style that has existed since the 70s, its a relatively new entrant in the .NET world. I had written a general introduction about MVC earlier. That post is available here. While Java, Ruby, Python all had their MVC frameworks for quite some time, ASP.NET was quite comfortable [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Though MVC is an age old architectural style that has existed since the 70s, its a relatively new entrant in the .NET world. I had written a general introduction about MVC earlier. That post is available <a href="http://blog.ganeshzone.net/blog/index.php/2009/11/asp-net-mvc-applications/">here</a>. While Java, Ruby, Python all had their MVC frameworks for quite some time, ASP.NET was quite comfortable with the Webform based architecture till recently. And Webforms arent really a bad way to code at all, you work with almost a Windows style of programming, dragging dropping controls. Double clicking them to code their event handlers. In fact due to this Rapid application development, ASP.NET was amazingly simple to work with. However, like with all other simple ways, ASP.NET webforms also take a lot of control away from the developer.</p>
<p style="text-align: justify;">MVC seeks to give developers an alternative, where they have complete control over the application including the viewstate of the controls. My first look was at ASP.NET MVC was a training session given by an architect from Microsoft, and I absolutely didn&#8217;t like the complexity it brought to a simple demo application that was showed. I found that we were writing too much code, again bringing back spaghetti code that died with ASP. But over time, after digging into MVC, I found that it made a lot of sense. If my need is just to display a set of data, why should I sacrifice performance over all of the gridview&#8217;s bulky viewstate. Rather, it makes sense to use a HTML table and apply CSS to style it.  That is exactly the flexibility that MVC gives you, instead of relying on built in abstraction done by Webform architecture, you get to control every detail of your application.</p>
<h2>WebForms</h2>
<p style="text-align: justify;">ASP.NET Webforms are radically different from any other server side scripting technology. For one, its event driven. Just like Windows programming, you assign an event handler to an element, like a button and it calls the handler when the button is clicked. No longer, do you have to keep on submitting the form to handle click events and write bulky code to do simple stuff. ASP.NET made the server side code clean &#8211; in fact a helluva lot cleaner than ASP.</p>
<p style="text-align: justify;">But all this ignores the age old truth about the web/HTTP &#8211; that it is stateless. The server forgets about the page the minute its sent to the client and thats the end of it. So how is context maintained in WebForms? The answer is <strong>Viewstate</strong>. All of the control states are Base64 encoded and recreated on the server again where the request is executed. There is a lot of built-in plumbing to achieve this level of abstraction.</p>
<p style="text-align: justify;">The main problem with webforms is that though it cleans up your code and markup and seperates them neatly in your Visual studio solution, it horribly clutters the rendered markup to the browser. Every control takes up more and more viewstate and the nested control names which are really long, make the markup bulky, and since this does a round trip on every request, it starts impacting performance and eventually scalability.</p>
<p style="text-align: justify;">One more concern is the Testability, due to the event driven approach, the GUI is tighly coupled with your business layer and there isnt any effective way to test your web page. Automating such testing could be an tedious effort and you would most probably end up doing manual testing.</p>
<p style="text-align: justify;">Despite all of these problems, Webforms are not a bad architecture. It is extremely mature and extensible. A lot of good documentation exists for it and it still makes sense for quite a few scenarios.</p>
<h2>MVC</h2>
<p style="text-align: justify;">With MVC, it was love at first byte. In fact I never realized how inefficient webforms were, until i worked with MVC. Instead of a page receiving the request, its the Controller which lives at the heart of MVC. Once it gets the request, it decides which view to render and may use models.</p>
<p style="text-align: justify;">One great thing about MVC is the clean Seperation of Concerns (SoC ) which you are able to achieve out of the box. Both the Controllers and the Views can be tested separately using testing tools like NUnit or MBUnit. So that means no longer. Manual testing doesn&#8217;t really make any sense for most scenarios, because the effort is not repeatable and when you want to try with a different input, you would need to start all over again.</p>
<p style="text-align: justify;">
<div id="_mcePaste" style="text-align: justify;">Also, you have complete control over the HTML that your controls generate. No more grappling with heavy Viewstate and decreased performance. Also there is no concept of a postback in MVC. Hence although, we can make use of ASP.NET server controls, we cant use either ViewState or Postback in them. Microsoft is working to create a library of MVC aware server controls that would be more suitable for this architectural style. Also, you have complete control over the HTML that your controls generate. No more grappling with heavy Viewstate and decreased performance. Also there is no concept of a postback in MVC. Hence although, we can make use of ASP.NET server controls, we cant use either ViewState or Postback in them. Microsoft is working to create a library of MVC aware server controls that would be more suitable for this architectural style.</div>
<p style="text-align: justify;">One major point that is oft repeated is that we shouldn&#8217;t jump the gun to convert every existing webforms applications into MVC just because its the in thing. You would have to rewrite your application completely, and the benefit derived would often not be worth the effort. But I would certainly  recommend that  you use MVC for any new applications you create. Its certainly the smarter way.</p>
<p style="text-align: justify;">
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Thread Synchronization techniques Part 2 &#8211; The ReaderWriterLock class</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 19:22:32 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=754</guid>
		<description><![CDATA[<p style="text-align: justify;">In continuation to my earlier post about multithreading in .NET, I am writing about the ReaderWriterLock class which is one more method of thread synchronization.</p>
<p style="text-align: justify;">The ReaderWriterLock is based on the fact that the Monitor locking (lock keyword in C#) doesnt really make any distinction whether the thread accessing the variable is [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">In continuation to my earlier post about multithreading in .NET, I am writing about the ReaderWriterLock class which is one more method of thread synchronization.</p>
<p style="text-align: justify;">The ReaderWriterLock is based on the fact that the Monitor locking (lock keyword in C#) doesnt really make any distinction whether the thread accessing the variable is reading it or writing to it. If its only reading it, then we should not need an exclusive lock. So If we allow multiple threads to read the value, it would be much faster than having mutually exclusive locks, which means a more scalable application? On paper, yes &#8211; but not in reality.</p>
<p style="text-align: justify;">The problem with ReaderWriterLock is with its implementation. Several experts have slammed this technique and found that outside of limited scenarios, it is actually far slower than the <strong>Monitor.Enter</strong> method used to get an exclusive lock. ReaderWriterLock gives higher priority to reader threads then writers. This makes sense if you have many readers and only a few writers. So a lot of readers are able to read the resource while the writer has to wait longer to get the lock. But what If you have equal or more writers. The process of favoring readers make writer threads queued up and take a very long time to complete.</p>
<p style="text-align: justify;">Jeffrey Richter says that this performance loss is due to support for Recursion in the ReaderWriterLock class. Due to this, the class needs to maintain a record of the number of times each thread acquires the lock and increment and decrement the counter. When multiple reader threads acquire the same lock (remember ReaderWriterLock class allows simultaneous reads), a counter is maintained for each thread. This overhead is what causes the ReaderWriterLock to pale in comparison to the Monitor class. It is approximately 6 times slower.</p>
<p style="text-align: justify;">Here is a code sample. The Threads 1 and 3 are reader threads while the Thread 2 is a writer one. When you take a look at the output, its clear that the readers are granted simultaneous access to the _value variable, but when the writer thread is writing to it, all the readers wait in queue patiently for it to finish executing. I have made the DoWorkRead method parametrized in order to identify the thread on which the method is being executed.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _value <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    ReaderWriterLock _rwLock <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ReaderWriterLock<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Program _prgm <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Program<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&amp;</span>lt<span style="color: #008000;">;</span> <span style="color: #FF0000;">20</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread _t1Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkRead</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//Reader Thread</span>
            <span style="color: #008080; font-style: italic;">//Writer Thread</span>
            Thread _t2Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkWrite</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Reader Again</span>
            Thread _t3Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkRead</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
&nbsp;
            <span style="color: #008080; font-style: italic;">//Start all threads</span>
            _t1Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread 1&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t3Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread 3&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Wait for them to finish execution</span>
            _t1Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t3Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkRead<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> threadName<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Accquire Reader Lock.</span>
        _rwLock.<span style="color: #0000FF;">AcquireReaderLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>threadName.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;Thread 1&quot;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #008080; font-style: italic;">//Irregular sleeps makes more chances of</span>
            <span style="color: #008080; font-style: italic;">//Multiple threads trying to access it</span>
            <span style="color: #008080; font-style: italic;">//at same time</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">else</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">250</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read end  : Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _rwLock.<span style="color: #0000FF;">ReleaseReaderLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">//Release Lock</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkWrite<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _rwLock.<span style="color: #0000FF;">AcquireWriterLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>Writer start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span> <span style="color: #008080; font-style: italic;">//Writing</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Writer End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _rwLock.<span style="color: #0000FF;">ReleaseWriterLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">
<p style="text-align: justify;">A look at the output shows the once the writer acquires a lock, it is mutually exclusive, but both the reader threads are able to access the variable _value.</p>
<p style="text-align: justify;">
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/01/Output1.jpg"><img class="aligncenter size-full wp-image-787" title="Output" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/01/Output1.jpg" alt="" width="314" height="334" /></a></p>
<p style="text-align: justify;">
<p style="text-align: justify;">One more problem with the ReaderWriterLock class is that it allows Reader threads to acquire writer locks. If you set an infinite timeout, it will create a deadlock situation, where the thread just waits to get the Writer lock but cant because the very same thread holds on to the Reader lock and is yet to release it. So the application just waits and waits.</p>
<p style="text-align: justify;">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkRead<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> threadName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//Accquire Reader Lock.</span>
            _rwLock.<span style="color: #0000FF;">AcquireReaderLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//NEVER EVER DO THE BELOW. IT WILL CREATE A DEADLOCK</span>
            _rwLock.<span style="color: #0000FF;">AcquireWriterLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _rwLock.<span style="color: #0000FF;">ReleaseReaderLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Release Lock</span>
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">Keeping all these issues in mind, Microsoft introduced a new class &#8211; the ReaderWriterLockSlim class from .NET 3.0 onwards, while leaving the old one in there as well, for backwards compatibility. This class placed Lock recursion in the hands of the developers by giving an enum that could be set during object recursion. With recursion out of the way, performance is dramatically better and comparable to the Monitor class. It also took care of the deadlock situation above. As a conclusion, it is always better to avoid the ReaderWriterLock class and use the slim implementation instead. If you are on .NET 2.0, then since that option is not open to you, its better to look at some other synchronization technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mars Rover Instruction problem &#8211; Solution</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/mars-rover-instruction-problem-solution/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/mars-rover-instruction-problem-solution/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 19:32:30 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[puzzles]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=756</guid>
		<description><![CDATA[<p>I got an interesting problem by email recently where someone had asked me to solve the given below problem:-</p>
<p>A squad of robotic rovers are to be landed by NASA on a plateau on Mars.This plateau, which is curiously rectangular, must be navigated by therovers so that their on-board cameras can get a complete view of [...]]]></description>
			<content:encoded><![CDATA[<p>I got an interesting problem by email recently where someone had asked me to solve the given below problem:-</p>
<p><em><span style="color: #993300;">A squad of robotic rovers are to be landed by NASA on a plateau on Mars.This plateau, which is curiously rectangular, must be navigated by therovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.</span></em></p>
<p><em><span style="color: #993300;">A rover&#8217;s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom<br />
left corner and facing North.</span></em></p>
<p><em><span style="color: #993300;"> </span><span style="color: #993300;">In order to control a rover, NASA sends a simple string of letters. The possible letters are &#8216;L&#8217;, &#8216;R&#8217; and &#8216;M&#8217;. &#8216;L&#8217; and &#8216;R&#8217; makes the rover spin 90 degrees left or right respectively, without moving from its current spot. &#8216;M&#8217; means move forward one grid point, and maintain the same heading.</span></em></p>
<p><em><span style="color: #993300;">Assume that the square directly North from (x, y) is (x, y+1).</span></em></p>
<p><em> </em></p>
<p><strong><em><span style="color: #993300;">INPUT:</span></em></strong><em><span style="color: #993300;"><br />
The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.</span></em></p>
<p><em><span style="color: #993300;">The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover&#8217;s position, and the second line is a series of instructions telling the rover how to explore the plateau.</span></em></p>
<p><em><span style="color: #993300;"> </span><span style="color: #993300;">The position is made up of two integers and a letter separated by spaces, corresponding to the x and  co-ordinates and the rover&#8217;s orientation.</span></em></p>
<p><em><span style="color: #993300;">Each rover will be finished sequentially, which means that the second rover won&#8217;t start to move until the first one has finished moving.</span></em></p>
<p><em> </em></p>
<p><strong><em><span style="color: #993300;">OUTPUT<br />
</span> </em><span style="color: #993300;"> </span></strong><em><span style="color: #993300;">The output for each rover should be its final co-ordinates and heading.</span></em></p>
<p>I worked out a simple solution for this problem. Of course there is a lot of room for improvement as this solution is the bare minimum one. The rover parses the instructions one at a time. Here are improvements I have planned to be implemented in later versions</p>
<ul>
<li>Understand multiple instruction and process them at once to improve performance</li>
<li>Identify cyclic instructions that have no net effect on coordinates and ignore them</li>
<li>Move multiple rover objects at same time.</li>
<li>Prevent two rovers from taking at same positions at the same time.</li>
</ul>
<p>Heres what I have for now.</p>
<p>The Rover class stores the state of each Rover on the grid.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #008080; font-style: italic;">/// This class is responsible for maintaining the state of each Rover</span>
    <span style="color: #008080; font-style: italic;">/// and processing the instructions given to it.</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #FF0000;">class</span> Rover
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//private objects : Coordinates, Direction, Instruction Array</span>
        <span style="color: #0600FF;">private</span> Coordinates _rovCor<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> Direction _rovDir<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _instructionArray<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//readonly properties for above objects</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> X <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _rovCor.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Y <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _rovCor.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> Direction RoverDirection <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _rovDir<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// Constructor. Passes to Struct coorinates for getting coordinate object</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> Rover<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xCor, <span style="color: #FF0000;">int</span> _yCor, <span style="color: #FF0000;">char</span> _startDir, <span style="color: #FF0000;">string</span> _instructionArray<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>._rovCor <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Coordinates<span style="color: #000000;">&#40;</span>_xCor, _yCor<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>._rovDir <span style="color: #008000;">=</span> GetDirection<span style="color: #000000;">&#40;</span>_startDir<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>._instructionArray <span style="color: #008000;">=</span> _instructionArray<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Parses The Start Position into Direction Enum</span>
        <span style="color: #0600FF;">private</span> Direction GetDirection<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">char</span> _startDir<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>_startDir<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">'N'</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> Direction.<span style="color: #0000FF;">North</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">'S'</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> Direction.<span style="color: #0000FF;">South</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">'E'</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> Direction.<span style="color: #0000FF;">East</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">'W'</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> Direction.<span style="color: #0000FF;">West</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">default</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Unknown Direction Supplied. Accepted values are N,S,E,W&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Processes the Instruction Array</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> ProcessInstructionArray<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">char</span> _instruction <span style="color: #0600FF;">in</span> _instructionArray<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                ProcessInstruction<span style="color: #000000;">&#40;</span>_instruction<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Processes individual instructions. delegates tasks to other methods</span>
        <span style="color: #008080; font-style: italic;">//after checking instruction type.</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> ProcessInstruction<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">char</span> _instruction<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>_instruction <span style="color: #008000;">==</span> <span style="color: #666666;">'L'</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> <span style="color: #000000;">&#40;</span>_instruction <span style="color: #008000;">==</span> <span style="color: #666666;">'R'</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                ProcessDirectionInstruction<span style="color: #000000;">&#40;</span>_instruction<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_instruction <span style="color: #008000;">==</span> <span style="color: #666666;">'M'</span><span style="color: #000000;">&#41;</span>
                ProcessMoveInstruction<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Invalid Instruction Processed. Please supply only L,R and M&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Move Instruction is processed by the Coordinate Object</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> ProcessMoveInstruction<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>._rovCor.<span style="color: #0000FF;">UpdateCoordinates</span><span style="color: #000000;">&#40;</span>_rovDir<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//This Processes the direction of the Rover. Instructions L and R</span>
        <span style="color: #008080; font-style: italic;">//are processed by this method.</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> ProcessDirectionInstruction<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">char</span> _instruction<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> _rovDirInt <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span><span style="color: #0600FF;">this</span>._rovDir<span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_instruction <span style="color: #008000;">==</span> <span style="color: #666666;">'L'</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_rovDirInt <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                    _rovDirInt <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">this</span>._rovDir <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>Direction<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#40;</span>_rovDirInt <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_rovDirInt <span style="color: #008000;">==</span> <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>
                    _rovDirInt <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">this</span>._rovDir <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>Direction<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#40;</span>_rovDirInt <span style="color: #008000;">+</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>The Rover class stores its coordinates and Directions as a struct and an enum. Here is the code for them.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #008080; font-style: italic;">/// This enumeration is for the Direction the Rover is currently facing in.</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #FF0000;">enum</span> Direction <span style="color: #000000;">&#123;</span> North, East, South, West, <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #008080; font-style: italic;">/// This is Stuct which holds the current coordinates of the Rover.</span>
    <span style="color: #008080; font-style: italic;">/// It is also used to hold the max coordinates of the Grid.</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #FF0000;">struct</span> Coordinates
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _xCor<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _yCor<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> X <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _xCor<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Y <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _yCor<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> Coordinates<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xCor, <span style="color: #FF0000;">int</span> _yCor<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>._xCor <span style="color: #008000;">=</span> _xCor<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>._yCor <span style="color: #008000;">=</span> _yCor<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> UpdateCoordinates<span style="color: #000000;">&#40;</span>Direction _dirObj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>_dirObj<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> Direction.<span style="color: #0000FF;">North</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">this</span>._yCor<span style="color: #008000;">++;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> Direction.<span style="color: #0000FF;">South</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">this</span>._yCor<span style="color: #008000;">--;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> Direction.<span style="color: #0000FF;">East</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">this</span>._xCor<span style="color: #008000;">++;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">case</span> Direction.<span style="color: #0000FF;">West</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">this</span>._xCor<span style="color: #008000;">--;</span>
                    break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>The Grid class contains a generic list of all the rovers on the grid. It moves each rover in the list and makes sure the rover doesn&#8217;t cross the boundaries. If it does then an exception is thrown.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #008080; font-style: italic;">/// This class is responsible for holding all the Rovers</span>
    <span style="color: #008080; font-style: italic;">/// and also making sure no rovers cross the grid boundaries.</span>
    <span style="color: #008080; font-style: italic;">/// The ToString() method is overridden to get the state of</span>
    <span style="color: #008080; font-style: italic;">/// all rovers on the grid in an easy to read string format</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #FF0000;">class</span> Grid
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Maximum coordinates for the grid</span>
        <span style="color: #0600FF;">private</span> Coordinates _maxCoordinates<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Collection Object to hold all rovers on grid</span>
        <span style="color: #0600FF;">private</span> List _allRoversOnGrid<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Constructor to intialize Rover collection and max coordinates</span>
        <span style="color: #0600FF;">public</span> Grid<span style="color: #000000;">&#40;</span>Coordinates _maxCor<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>._maxCoordinates <span style="color: #008000;">=</span> _maxCor<span style="color: #008000;">;</span>
            _allRoversOnGrid <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Rovers can only be added to the collection. Nothing else</span>
        <span style="color: #008080; font-style: italic;">//is exposed outside</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddToRoverCollection<span style="color: #000000;">&#40;</span>Rover _roverObj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _allRoversOnGrid.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_roverObj<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//This method processes all the rovers on the grid and their instruction arrays</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> MoveAllRoversOnGrid<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Rover _tempRov <span style="color: #0600FF;">in</span> _allRoversOnGrid<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _tempRov.<span style="color: #0000FF;">ProcessInstructionArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">DoIntegrityCheck</span><span style="color: #000000;">&#40;</span>_tempRov<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Making sure the Rover object stays within the grid.</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> DoIntegrityCheck<span style="color: #000000;">&#40;</span>Rover _tempRov<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>_tempRov.<span style="color: #0000FF;">X</span> <span style="color: #008000;">&amp;</span>gt<span style="color: #008000;">;</span> _maxCoordinates.<span style="color: #0000FF;">X</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> <span style="color: #000000;">&#40;</span>_tempRov.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">&amp;</span>gt<span style="color: #008000;">;</span> _maxCoordinates.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Rover Failed Grid Integrity. Moved out of Grid Boundaries&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Overriding the ToString method to get all rovers states</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">string</span> ToString<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            StringBuilder _AllRoversState <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;**********************************&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Number of Rovers currently on Grid: &quot;</span> <span style="color: #008000;">+</span> <span style="color: #0600FF;">this</span>._allRoversOnGrid.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Max Coordinates: X: {0},Y: {1}&quot;</span>, _maxCoordinates.<span style="color: #0000FF;">X</span>, _maxCoordinates.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Each Rover state as below: &quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Rover _tempRov <span style="color: #0600FF;">in</span> _allRoversOnGrid<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Rover Details -- X:{0},Y:{1},Direction:{2}&quot;</span>, _tempRov.<span style="color: #0000FF;">X</span>, _tempRov.<span style="color: #0000FF;">Y</span>, _tempRov.<span style="color: #0000FF;">RoverDirection</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            _AllRoversState.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;**********************************&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> _AllRoversState.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Finally, the code to call the Grid class:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Creating Grid Object</span>
            Grid _testGrid <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Grid<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Coordinates<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span>,<span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Adding two rovers as per sample input</span>
            _testGrid.<span style="color: #0000FF;">AddToRoverCollection</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Rover<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span>, <span style="color: #666666;">'N'</span>, <span style="color: #666666;">&quot;LMLMLMLMM&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _testGrid.<span style="color: #0000FF;">AddToRoverCollection</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Rover<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">3</span>, <span style="color: #666666;">'E'</span>, <span style="color: #666666;">&quot;MMRMMRMRRM&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//move all rovers</span>
            _testGrid.<span style="color: #0000FF;">MoveAllRoversOnGrid</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Get Rover Final state using Grids ToString() method.</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>_testGrid.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>To download the solution click <a href="http://www.ganeshzone.net/Files/Presoft.RoverProblem.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/mars-rover-instruction-problem-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multithreading in .NET and Synchronization techniques &#8211; Part 1</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 20:20:18 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=731</guid>
		<description><![CDATA[<p style="text-align: justify;">How often have you faced  the irritating not responding screen while the application waits for the data that you requested for. The problem is not with bad code or a slow database, the problem with conventional applications is that all the code is executed on a single thread. i.e. whenever an operation is [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">How often have you faced  the irritating not responding screen while the application waits for the data that you requested for. The problem is not with bad code or a slow database, the problem with conventional applications is that all the code is executed on a single thread. i.e. whenever an operation is performed the calling function must wait for it to complete in order to resume execution.</p>
<p style="text-align: justify;">Since the main thread is also the UI thread, the UI stops responding whenever its waiting for the function to return, making the user experience very bad. To avoid this, any time consuming operation should be executed on its own thread rather than the main thread. Lets see a simple example of a method created on another thread.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            ThreadingApp _testObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadingApp<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Declaring Two Objects for calling the parameterless and parametrized method</span>
            Thread _tObj1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ParameterizedThreadStart<span style="color: #000000;">&#40;</span>_testObj.<span style="color: #0000FF;">DoSomeWork</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread _tObj2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_testObj.<span style="color: #0000FF;">DoWork</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Calling the overloaded method</span>
            _tObj1.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;CustomParameter&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Calling the parameterless method</span>
            _tObj2.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #FF0000;">class</span> ThreadingApp<span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Parameterless method executed on anothed</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Executed On another thread&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoSomeWork<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> _name<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Executed on another thread. Paramter: &quot;</span> <span style="color: #008000;">+</span> _name<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The ability to pass parameters to methods on other threads is new in .NET 2.0. The delegate introduced for this is the <strong>ParametrizedThreadStart</strong> delegate which takes in an object parameter. Since its an object type, pretty much anything can be passed to the method. So creating new threads is pretty simple. But a word of caution here &#8211;  Threading unless used carefully can introduce very hard to detect bugs in your system.</p>
<p style="text-align: justify;">Multiple threads don&#8217;t cause any problem till the time each thread runs its own context not depending on shared resources or variables. The issues start when threads start to modify each others variables and access each others resources. Lets see a small example where multiple threads accessing the same variable can lead to unpredictable scenarios. In the below code two variables increment a class level variable and print the values before and after the incrementing. As you can see in the output below, it leads to a chaotic scenario where threads are misreading values and coming in each others way to access the variable.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _value <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        Program _prgm <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Program<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread _t1Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWork1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread _t2Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWork2</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _t1Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span>
        <span style="color: #008080; font-style: italic;">//Introduced a small sleep to bring some entropy in the system</span>
        Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork2<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread2 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread2 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">When we see the output, it looks pretty haphazard. Its easy to see the threads are confused about execution and misreading the value of the variable.</p>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/output.jpg"><img class="aligncenter size-full wp-image-739" title="output" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/output.jpg" alt="" width="342" height="307" /></a></p>
<p style="text-align: justify;">The Monitor class can be used to synchronize threads in .NET. How it works is that it puts a lock on the currently executing code making all other threads wait before they can access the variables that current method has locked. The Monitor has two main static methods Monitor.Enter and Monitor.Exit for entering the lock and exiting from it. Apart from this there is also the Monitor.TryEnter which tries to gain ownership of the code block. If its not able to it returns false. This is very important since calling the Monitor.Exit for a block you dont have ownership of, would raise a <strong>SynchronizationLockException. </strong>However making sure to call Enter and Exit every time would get cumbersome for a developer and there are chances it might be forgotten. Here is where C# comes into rescue with the lock keyword. Enclosing the code within the lock block automatically does all the steps which are mentioned above.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">readonly</span> <span style="color: #FF0000;">object</span> _lockObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">lock</span> <span style="color: #000000;">&#40;</span>_lockObj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _value<span style="color: #008000;">++;</span>
            <span style="color: #008080; font-style: italic;">//Introduced a small sleep to bring some entropy in the system</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Enclosing the code within the lock block brings order back to the method execution and we can observe that that each thread waits for the other to complete before attempting to modify the variable. Here is the IL for the above method.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">public</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span>  DoWork1<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
&nbsp;
  IL_0000:  <span style="color:blue;">ldsfld</span>     <span style="color:purple;font-weight:bold;">object</span> ThreadingApp.Program::_lockObj
  IL_0005:  <span style="color:blue;">dup</span>
  IL_0007:  <span style="color:blue;">call</span>       <span style="color:purple;font-weight:bold;">void</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Threading.Monitor::<span style="color: #000033;">Enter</span><span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">object</span><span style="color: #006400;">&#41;</span>
  <span style="color:maroon;font-weight:bold;">.try</span>
  <span style="color: #006400;">&#123;</span>
    <span style="color:gray;font-style:italic;">//Our method logic removed for brevity</span>
  <span style="color: #006400;">&#125;</span>  <span style="color:gray;font-style:italic;">// end .try</span>
  <span style="color:blue;font-weight:bold;">finally</span>
  <span style="color: #006400;">&#123;</span>
    IL_0057:  <span style="color:blue;">ldloc</span>.<span style="color:blue;">0</span>
    IL_0058:  <span style="color:blue;">call</span>       <span style="color:purple;font-weight:bold;">void</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Threading.Monitor::<span style="color: #000033;">Exit</span><span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">object</span><span style="color: #006400;">&#41;</span>
    IL_005d:  <span style="color:blue;">endfinally</span>
  <span style="color: #006400;">&#125;</span>  <span style="color:gray;font-style:italic;">// end handler</span>
  IL_005e:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method Program::DoWork1</span></pre></td></tr></table></div>

<p>A very important point stressed time and again would be to make sure not to expose the locking object outside the class. If this is done, anyone can use the object to lock your methods and not release them while your application threads remain indefinitely waiting for the lock to be freed.</p>
<p>There are many other techniques for thread synchronization in .NET. I will be covering them in upcoming posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Differences between Events and delegates</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 21:33:15 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Delegates]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=710</guid>
		<description><![CDATA[<p style="text-align: justify;">Events and Delegates are quite tied together in .NET, but there are differences in terms of usage. Events are implemented through delegates, but they are not quite interchangeable. The event keyword is an access modifier on the delegate which restricts its usage outside the class which it belongs to.</p>
<p style="text-align: justify;">First the similarities. [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Events and Delegates are quite tied together in .NET, but there are differences in terms of usage. Events are implemented through delegates, but they are not quite interchangeable. The event keyword is an access modifier on the delegate which restricts its usage outside the class which it belongs to.</p>
<p style="text-align: justify;">First the similarities. See the below code, which declares a delegate and creates objects for it with and without the event modifier. Then uses both of them, without any difference whatsoever.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> Test
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> MyDelegate<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _someRandomMessage<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//One is a delegate while other is an event.</span>
        <span style="color: #0600FF;">public</span> MyDelegate _mydelObj<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">event</span> MyDelegate _myeventObj<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> Test<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _mydelObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Delegate Invoked: &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _myeventObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Event Invoked: &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> TestDelegates<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _mydelObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;I am a delegate&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _myeventObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;I am an event&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">The main difference starts when you access events outside of the class they were declared in. I created one more class SomeOtherClass (very unimaginative!!) and invoked the public delegate objects from this. When its a plain delegate object, there is no restriction on resetting the invocation list, adding to it, removing from it and also invoking the delegate itself. But try doing that to the event object, and you the compiler will throw the <em><strong>The event &#8216;EventsAndDelegates.Test._myeventObj&#8217; can only appear on the left hand side of += or -= (except when used from within the type &#8216;EventsAndDelegates.Test&#8217;)</strong></em></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> SomeOtherClass<span style="color: #000000;">&#123;</span>
        Test _testObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Test<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> SomeOtherClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _testObj._mydelObj <span style="color: #008000;">+=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Calling from Outside class: &quot;</span><span style="color: #008000;">+</span>s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _testObj._myeventObj <span style="color: #008000;">+=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Calling Event from Outside class &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//The below code wont work. An event's invocation list cannot be accessed</span>
            <span style="color: #008080; font-style: italic;">//from outside. It can be added to or removed from.</span>
            _testObj._myeventObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Trying to reset the invocation list&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> InvokeBaseDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _testObj._mydelObj<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Delegate Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//This will throw an error. An event cannot be triggered from anyother type</span>
            <span style="color: #008080; font-style: italic;">//other than the one which it belongs to</span>
            _testObj._myeventObj<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Event Triggered&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>This key difference is due to the way events and delegates are exposed outside the class which they are declared in. There is an extra IL declaration for an event object which declares two accessors add and remove for the event. Only these are accessible outside the class.</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.event</span> EventsAndDelegates.Test/MyDelegate _myeventObj
<span style="color: #006400;">&#123;</span>
  <span style="color:maroon;font-weight:bold;">.addon</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">add__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
  <span style="color:maroon;font-weight:bold;">.removeon</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">remove__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of event Test::_myeventObj</span></pre></div></div>

<p style="text-align: justify;">When this is accessed in <em>SomeOtherClass</em>, the Delegate.Combine method used to add to the delegate object&#8217;s invocation list is not available for the event and the only alternatives are the add and remove accessors. Similarly the Invoke method is not available outside the class because of which the events cant be triggered.</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">public</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">specialname</span> <span style="color:blue;font-weight:bold;">rtspecialname</span>
        <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span>  <span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
<span style="color:gray;font-style:italic;">//Removed for Brevity</span>
  IL_0035:  <span style="color:blue;">ldsfld</span>     <span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate EventsAndDelegates.SomeOtherClass::'CS$&amp;lt;&amp;gt;<span style="color: #00008B;">9</span>__CachedAnonymousMethodDelegate2'
  IL_003a:  <span style="color:blue;">call</span>       <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate::<span style="color: #000033;">Combine</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate,
                                                                                          <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate<span style="color: #006400;">&#41;</span>
  IL_003f:  <span style="color:blue;">castclass</span>  EventsAndDelegates.Test/MyDelegate
<span style="color:gray;font-style:italic;">//Removed for brevity</span>
  IL_0067:  <span style="color:blue;">ldsfld</span>     <span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate EventsAndDelegates.SomeOtherClass::'CS$&amp;lt;&amp;gt;<span style="color: #00008B;">9</span>__CachedAnonymousMethodDelegate3'
<span style="color:gray;font-style:italic;">//Notice the add_ accessor being called instead of the Delegate.Combine method</span>
  IL_006c:  <span style="color:blue;">callvirt</span>   <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">add__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
  IL_0071:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method SomeOtherClass::.ctor</span></pre></div></div>

<p style="text-align: justify;">It makes sense to restrict an event&#8217;s invocation list from an outside class. For example, if your application makes use of a public API which polls for the weather at a location and raises an event when there is going to be heavy snow. Someone in your team might have subsribed to the event to send out notifications to employees take caution while travelling. However, your need to subscribe to the event could be totally different. In that case if you use the <strong>=</strong> sign instead of the <strong>+=</strong> while assigning a handler, the previous code for sending out notifications would not work. Needless to say, there would be a lot of pi**ed off employees baying for your blood the next day.</p>
<p style="text-align: justify;">Apart from this, there is one more difference between delegates and events while declaring them in an interface. An interface cannot contain delegate objects, however they can contain events. If you try to do so, you would get an error <strong><em>Interfaces cannot contain fields.</em></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lambda expressions in C#</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/lambda-expressions-in-c/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/lambda-expressions-in-c/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 14:24:53 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[VS 2008]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=696</guid>
		<description><![CDATA[<p>In the previous post we saw how anonymous methods can help reduce verbose delegate code. With C# 3.0, there was a new language feature introduced which further reduces the delegate code &#8211; Lambda expressions. </p>
<p>Lambda expressions use automatic type inference, which relieves you of explicitly declaring the type. Here is a simple example of lambda [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post we saw how anonymous methods can help reduce verbose delegate code. With C# 3.0, there was a new language feature introduced which further reduces the delegate code &#8211; Lambda expressions. </p>
<p>Lambda expressions use automatic type inference, which relieves you of explicitly declaring the type. Here is a simple example of lambda expressions usage. Notice how the code for the delegate object is concisely declared. What is signifies is that the value of x is to be passed to the method, which is then squared and returned. The operator => signifies sending of the parameter (LHS) to the method (RHS).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">	<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #FF0000;">int</span> Square<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> x<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">// Simple Lambda expression example</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Test<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Note I dont declare the type of variable x. Its automatically inferred.</span>
		Square myVar <span style="color: #008000;">=</span> x <span style="color: #008000;">=&gt;</span> x<span style="color: #008000;">*</span>x<span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">//Call the delegate</span>
		<span style="color: #FF0000;">int</span> n <span style="color: #008000;">=</span> myVar<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>n<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//prints 25</span>
	<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>When we dive into the MSIL, we find an identical code to Anonymous methods. There is a delegate which is created by the compiler automatically and also the implementation of the inline code is spun off into a separate method b_0. Whats important to note is that both the return type and the arguments of the method is automatically inferred by the compiler. This is not possible with anonymous methods, where we have to explicitly declare the list of arguments to the delegate.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">private</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">static</span> <span style="color:purple;font-weight:bold;">int32</span>  '&lt;test&gt;b__0'<span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">int32</span> x<span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
  IL_0000:  <span style="color:blue;">ldarg</span>.<span style="color:blue;">0</span>
  IL_0001:  <span style="color:blue;">ldarg</span>.<span style="color:blue;">0</span>
  IL_0002:  <span style="color:blue;">mul</span>
  IL_0003:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method TestLambda::'&lt;/test&gt;&lt;test&gt;b__0'</span>
&lt;/test&gt;</pre></td></tr></table></div>

<p>Since lambda expression pass the parameter to the method, the syntax is slightly different for delegates which don&#8217;t take any parameters.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> DoSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> MethodsWithNoArguments<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        DoSomething _methWithNoArgs <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">&quot;Lambda Expression without arguments and return types&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//prints the message.</span>
        _methWithNoArgs<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Lambda expressions can also be used to send a delegate object as a parameter to any method. In the below example, I wrote a delegate which takes in a delegate as a parameter and invokes it using the other argument. Note how lambda expressions automatically inferred the type of the delegate object being passed to it.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> PrintMessage<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> DoSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #008080; font-style: italic;">//Takes in the Print Message Delegate as an argument.</span>
 <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> LamArguments<span style="color: #000000;">&#40;</span>PrintMessage _printMsg,<span style="color: #FF0000;">string</span> _message<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> TestDelegateParams<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//This delegate takes in the PrintMEssage delgate as the </span>
        <span style="color: #008080; font-style: italic;">// parameter and invokes it. </span>
        LamArguments _lamARg <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>mymsg, _message<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
        <span style="color: #000000;">&#123;</span>
            mymsg.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>_message<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Assigning a method to the PrintMessage delegate's invocation list.</span>
        PrintMessage _printMsg <span style="color: #008000;">=</span> _message <span style="color: #008000;">=&gt;</span>
            <span style="color: #000000;">&#123;</span>
                Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>_message<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Sending the message </span>
        _lamARg<span style="color: #000000;">&#40;</span>_printMsg, <span style="color: #666666;">&quot;Hello World&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/lambda-expressions-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
