<?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>Ruchit Surati&#039;s blog &#187; c#</title>
	<atom:link href="http://www.ruchitsurati.net/index.php/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ruchitsurati.net</link>
	<description>thoughts and ideas of a .net developer</description>
	<lastBuildDate>Wed, 23 Feb 2011 19:48:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>understanding ‘using’ block in C#</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 16:46:47 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[net-framework]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=422</guid>
		<description><![CDATA[using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can&#8217;t predict when exactly the object will be garbage collected. Many times we need to make [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">using block in C# comes very handly while dealing with <em>disposable</em> objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can&#8217;t predict when exactly the object will be garbage collected. Many times we need to make sure the object is disposed along with all the resources it uses immediately after the purpose is served. This becomes possible with using block. <em>using </em>block in C# lets you deal with <em>disposable</em> objects effectively. But how does it work ? <strong>How does using block ensure the object is immediately disposed after the scope of the using block?</strong></p>
<p style="text-align: justify;">Lets look at what MSDN has to say. As per the msdn</p>
<blockquote style="text-align: justify;"><p><em>using</em> block Defines a scope, outside of which an object or objects will be disposed.</p></blockquote>
<p style="text-align: justify; clear: both;"><em>The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using  statement must implement the IDisposable  interface. This interface provides the Dispose  method, which should release the object&#8217;s resources.</em></p>
<p style="text-align: justify;">Surprisingly even MSDN does not clarify how does this happen under the hood. It only says the object has to implement <em>IDisposable </em>interface that provides <em>Dispose </em>method on the object implementing the interface.  So to dispose the object it will need to call the Dispose method on the object which will cleanup and release the resources used by the object.</p>
<p style="text-align: justify;">This led me to write some code and analyze the generated IL where I found the answers. Have a look at this code. I&#8217;ve written a class <em>Car </em>and made it <em>IDisposable </em>so that I can club its&#8217; lifetime with <em>using</em> block.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    public class Car : IDisposable
    {
        public Car(int id)
        {
            this.Id = id;
        }

        public int Id { get; set; }

        public void Run()
        {
            Console.WriteLine(&quot;Car {0} is running.&quot;, this.Id.ToString());
        }

        #region IDisposable Members

        public void Dispose()
        {
            Console.WriteLine(&quot;Releasing resources used by Car object : &quot; + this.Id.ToString());
        }

        #endregion
    }
}
</pre>
<p style="text-align: justify;">Here&#8217;s my client-code. A sample ConsoleApplication that uses the Car object within the using block.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Car myCar = new Car(1))
            {
                myCar.Run();
            }
        }
    }
}
</pre>
<p style="text-align: justify;">The output was obvious. Immediately after the using block the Dispose method of the Car object is called. Note that there are no signs of Dispose() method being called explicitly, still the method is called. Lets look at the generated IL.</p>
<pre class="brush: csharp; title: ;">
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       37 (0x25)
  .maxstack  2
  .locals init ([0] class BlogSamples.Car myCar,
           [1] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  newobj     instance void BlogSamples.Car::.ctor(int32)
  IL_0007:  stloc.0
  .try
  {
    IL_0008:  nop
    IL_0009:  ldloc.0
    IL_000a:  callvirt   instance void BlogSamples.Car::Run()
    IL_000f:  nop
    IL_0010:  nop
    IL_0011:  leave.s    IL_0023
  }  // end .try
  finally
  {
    IL_0013:  ldloc.0
    IL_0014:  ldnull
    IL_0015:  ceq
    IL_0017:  stloc.1
    IL_0018:  ldloc.1
    IL_0019:  brtrue.s   IL_0022
    IL_001b:  ldloc.0
    IL_001c:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
    IL_0021:  nop
    IL_0022:  endfinally
  }  // end handler
  IL_0023:  nop
  IL_0024:  ret
} // end of method Program::Main
</pre>
<p style="text-align: justify;">Do you spot that compiler has introduced <em>try/finally</em> block and replaced it with <em>using </em>block. But why did compiler do that ? Lets observe the code and attempt to write similar C# code for better understanding. After careful analysis and reverse-engineering the equivalent C# code would look something as following.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare myCar object with FullName of the type as seen in IL.
            BlogSamples.Car myCar;

            //Instantiate the object by calling the constructor, matching the flow of IL.
            myCar = new Car(1);

            try
            {
                myCar.Run();
            }
            finally
            {
                if(myCar != null)
                    myCar.Dispose();
            }
        }
    }
}
</pre>
<p style="text-align: justify;">Above code is very clear. All it does is replace the code within the using block into the try block and calls the Dispose() method of the object in the finally block. As we all know, the code written in finally block gets executed in any situation even in case of any handled or un-handled exception. And this is how the using block ensures that the objects used with the using block are disposed for sure.</p>
<blockquote><p>In fact using block is just a syntactic sugar for this pattern of code.</p></blockquote>
<p style="text-align: justify; clear: both;">
<p>Some of you might wonder, how does the generated IL of the new reverse-engineered code look like. The IL of the reverse-engineered looks like this.</p>
<pre class="brush: csharp; title: ;">
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       31 (0x1f)
  .maxstack  2
  .locals init ([0] class BlogSamples.Car myCar)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  newobj     instance void BlogSamples.Car::.ctor(int32)
  IL_0007:  stloc.0
  .try
  {
    IL_0008:  nop
    IL_0009:  ldloc.0
    IL_000a:  callvirt   instance void BlogSamples.Car::Run()
    IL_000f:  nop
    IL_0010:  nop
    IL_0011:  leave.s    IL_001d
  }  // end .try
  finally
  {
    IL_0013:  nop
    IL_0014:  ldloc.0
    IL_0015:  callvirt   instance void BlogSamples.Car::Dispose()
    IL_001a:  nop
    IL_001b:  nop
    IL_001c:  endfinally
  }  // end handler
  IL_001d:  nop
  IL_001e:  ret
} // end of method Program::Main
</pre>
<blockquote><p>Needless to mention that the IL in both the cases is identical to each other which proves the point that the using block is nothing but a syntactic sugar.</p></blockquote>
<p style="text-align: justify; clear: both;"><strong>You might ask what if the constructor throws an exception.</strong> In this case the control would not move forward and never enter the proceeding try block. The object myCar still remains null. However you can wrap the using block in a try/catch block as shown below and handle the situation gracefully.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (Car myCar = new Car(1))
                {
                    myCar.Run();
                }
            }
            catch
            {
                //Handle the situation gracefully.
            }
        }
    }
}
</pre>
<blockquote><p>But why C# designers did not wrap object construction within the try block.</p></blockquote>
<p style="text-align: justify; clear: both;">
The reason is simple. If you wrap both declaration and instantiation within the try block then <strong>the object would be out of scope for the proceeding finally block</strong> and the code will not compile at because, for finally block the object hardly exists. If you only wrap the construction in the try block and keep declaration before the try block, even in that case the it will not compile since it finds <strong>use of an unassigned variable which is not allowed in C#</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Decorator Pattern with C#</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 17:34:47 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[ooad]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=431</guid>
		<description><![CDATA[Decorator pattern achieves a single objective of dynamically adding responsibilities to any object. Consider a case of a pizza shop. In the pizza shop they will sale a few pizza varieties and have toppings that customers can order additionally on top of a pizza. Customer can order a pizza and add as many as toppings [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>Decorator pattern achieves a single objective of dynamically adding  responsibilities to any object.</strong></p></blockquote>
<p style="text-align: justify;">Consider a case of a pizza shop. In the pizza shop they will sale a few pizza varieties and have toppings that customers can order additionally on top of a pizza. Customer can order a pizza and add as many as toppings on the pizza. The cost of the ordered pizza will have to be calculated with pizza and all additional toppings. Now imagine a situation wherein if the pizza shop has to provide prices for each combination of pizza and topping. Even if there are four basic pizzas and 8 different toppings, the application would go crazy maintaining all concrete combination of pizzas and toppings. It is impractical to keep all combination in the menu. You&#8217;ll do enough to lose the customer when you expect him to go through such a long menu and do humongous brain-job.</p>
<p style="text-align: justify;">Here comes the decorator pattern.</p>
<p style="text-align: justify;">As per the decorator pattern, you will implement toppings as decorators and pizzas will be decorated by those toppings&#8217; decorators. Practically each customer would want toppings of his desire and final bill-amount will be composed of the base pizzas and additionally ordered toppings. Each topping decorator would know about the pizzas that it is decorating and it&#8217;s price. </p>
<p style="text-align: justify;">Here&#8217;s a code-example of explanation above.</p>
<pre class="brush: csharp; title: ;">

//All your pizzas will inherit from this BasePizza class to identify themselves as pizzas.
public abstract class BasePizza
{
    protected double myPrice;

    //This method will return the price of the pizza object.
    public virtual double GetPrice()
    {
        return this.myPrice;
    }
}

//All toppings will inherit from this ToppingsDecorator class to be able to be added to any pizza in the pizza-shop.
public abstract class ToppingsDecorator : BasePizza
{
    //Each topping will need to know to which pizza it is being added to.
    protected BasePizza pizza;
    public ToppingsDecorator(BasePizza pizzaToDecorate)
    {
        this.pizza = pizzaToDecorate;
    }

    //This method will return cumulative price of both pizza and the topping.
    public override double GetPrice()
    {
        return (this.pizza.GetPrice() + this.myPrice);
    }
}

class Program
{
    [STAThread]
    static void Main()
    {
        //Client-code

        //First - order your base pizza. We'll add toppings onto this pizza.
        Margherita pizza = new Margherita();
        Console.WriteLine(&quot;Plain Margherita: &quot; + pizza.GetPrice().ToString());

        //Add extra cheese.
        ExtraCheeseTopping moreCheese = new ExtraCheeseTopping(pizza);

        //Add some more cheese and make it double extra cheese.
        ExtraCheeseTopping someMoreCheese = new ExtraCheeseTopping(moreCheese);
        Console.WriteLine(&quot;Plain Margherita with double extra cheese: &quot; + someMoreCheese.GetPrice().ToString());

        //Like mushrroms ? Add that too.
        MushroomTopping moreMushroom = new MushroomTopping(someMoreCheese);
        Console.WriteLine(&quot;Plain Margherita with double extra cheese with mushroom: &quot; + moreMushroom.GetPrice().ToString());

        //Throw in some Jalapeno and make it sour and spicy.
        JalapenoToping moreJalapeno = new JalapenoToping(moreMushroom);

        //Add here's your final pizza.
        Console.WriteLine(&quot;Plain Margherita with double extra cheese with mushroom with Jalapeno: &quot; + moreJalapeno.GetPrice().ToString());

    }
}

public class Margherita : BasePizza
{
    public Margherita()
    {
        this.myPrice = 6.99;
    }
}

public class Gourmet : BasePizza
{
    public Gourmet()
    {
        this.myPrice = 7.49;
    }
}

public class ExtraCheeseTopping : ToppingsDecorator
{
    public ExtraCheeseTopping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 0.99;
    }
}

public class MushroomTopping : ToppingsDecorator
{
    public MushroomTopping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 1.49;
    }
}

public class JalapenoToping : ToppingsDecorator
{
    public JalapenoToping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 1.49;
    }
}
</pre>
<p>
Note that, <strong>GetPrice()</strong> method of Topping object would return cumulative price of both pizza and the topping.
</p>
<p><img src="http://ruchitsurati.net/myfiles/decorator.png" alt="alt text" /></p>
<p>
<script type="text/javascript"><!--
google_ad_client = "pub-3020293614675538";
/* 300x250, created 14-July-2010 */
google_ad_slot = "4146580937";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Sealed classes as Generic type-constraints</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 14:23:08 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=348</guid>
		<description><![CDATA[We make heavy use of generics in our projects. Generics are really great deal when it comes to run-time polymorphism. Recently, one of my colleague came up with an idea to use a sealed class as generic type constraint. He wrote a sample code that looks like this. public sealed class MySealedClass { public MySealedClass() [...]]]></description>
			<content:encoded><![CDATA[<p>We make heavy use of generics in our projects. Generics are really great deal when it comes to run-time polymorphism. Recently, one of my colleague came up with an idea to use a sealed class as generic type constraint. He wrote a sample code that looks like this.</p>
<pre class="brush: csharp; highlight: [1,7]; title: ;">
public sealed class MySealedClass
{
    public MySealedClass() { }
}

public class MyGeneric&lt;T&gt;
        where T : MySealedClass
{
    public MyGeneric() { }
}
</pre>
<p style="text-align: justify;">Surprisingly, Above code gives following compile error.</p>
<p class="message notice" style="text-align: justify;">&#8216;MySealedClass&#8217; is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</p>
<p style="text-align: justify;">That was strange. We never observed such behavior before. Code was absolutely correct and it seemed like language designers had intentionally put this constraint to not allow sealed classed as generic constraints. But what must be the reason behind this ? Finally we had our thoughts in place and found the fact why it is so.</p>
<p style="text-align: justify;">To understand, why sealed classes are not allowed to be generic type constraints, let us assume that sealed classes are allowed to be type constraints to generics. With this assumption the code above is valid and compiles successfully. Now lets write some client-code that would use this generic.</p>
<pre class="brush: csharp; title: ;">
//create and instantiate an object of type MyGeneric
MyGeneric&lt;MySealedClass&gt; objGeneric = new MyGeneric&lt;MySealedClass&gt;();
</pre>
<p style="text-align: justify;">Fair enough, this looks ok.</p>
<p style="text-align: justify;">Now lets check what other types we can pass to MyGeneric type-argument at runtime. By defination, it has to be MySealedClass itself or any type that inherits from MySealedClass.</p>
<p style="text-align: justify;">But won&#8217;t MySealedClass be the only valid type-argument for MyGeneric since MySealedClass cannot be inherited further and there will be no class that inherits from MySealedClass ? Doesn&#8217;t this defeat the whole idea of putting MySealedClass in type constraint to MyGeneric, since there&#8217;ll be no other valid-type argument except MySealedClass itself ? If MySealedClass is going to be the only valid type for MyGeneric, then  there&#8217;s no point in  defining MyGeneric as generic at all. Can&#8217;t we simply code against the type MySealedClass ?</p>
<p style="text-align: justify;">We could finally realize the reason why language designers of  C# didn&#8217;t allow sealed classes as generic type-argument. quite enlightening.</p>
<p style="text-align: justify;">While doing this we also came to realize why static classes are also not allowed to be generic type-constraints, though it&#8217;s very much obvious that static classes can never ever be generic type constraints. We found our answer in the compiled IL, where the <strong>static classes are marked as both abstract and sealed. Abstract since they cannot be instantiated and sealed since they cannot be inherited, hence cannot be generic type-constraints. </strong>In general only those types can be generic type-constraints which can have inheritance hierarchy below them, this includes interfaces, any non-sealed abstract or concrete classes.</p>
<p>
<script type="text/javascript"><!--
google_ad_client = "pub-3020293614675538";
/* 300x250, created 14-July-2010 */
google_ad_slot = "4146580937";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

