<?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; net-framework</title>
	<atom:link href="http://www.ruchitsurati.net/index.php/tag/net-framework/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>My Presentations at tops-int on .Net</title>
		<link>http://www.ruchitsurati.net/index.php/2008/04/23/my-presentations-at-tops-int-on-net/</link>
		<comments>http://www.ruchitsurati.net/index.php/2008/04/23/my-presentations-at-tops-int-on-net/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 09:50:29 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[net-framework]]></category>
		<category><![CDATA[presentation]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/post.aspx?id=eb40d488-d919-451b-ac77-c6af81b20503</guid>
		<description><![CDATA[Sharing and gaining, knowledge and information has always been my passion. I just love this. Sometimes you get to talk to unbelievably talented people and it just makes your day. I have been attending sessions on different technology topics and development platforms for a long time now. It always worth doing so. More you do [...]]]></description>
			<content:encoded><![CDATA[<p>Sharing and gaining, knowledge and information has always been my passion. I just love this. Sometimes you get to talk to unbelievably talented people and it just makes your day. I have been attending sessions on different technology topics and development platforms for a long time now. It always worth doing so. More you do more you get hungry for. After all its a hungry mind out there in all of us. </p>
<p>You always help the next generation by sharing and giving whatever they need with whatever you can deliver. I got an opportunity to deliver a session on .net fundamentals last week at a good company out here. They wanted me to take a session on .net fundamentals and basics. Definitely, I opted for that. Believe me though I&#8217;ve been working on that platform for a long while now, to comprehend the contents in a presentation and a session of two hours was quite a challenging task. After putting lot of efforts, I could some how managed to do that. </p>
<p>It started out well, and eventually I dragged it towards an endless discussion which everybody just enjoyed it. We discussed in detail on CTS, CLS and many more issues. I inspired them to ask questions be it silly or meaningful, but they must ask. I had to gain them the confidence for working on .net platform since some of them were just college pass-outs and freshers hence. </p>
<p>With that note, I&#8217;m publishing my presentation on this blog which I showcased in the event. Hope it might help some one out there!</p>
<p>Topics: <strong>Microsoft .Net Fundamentals and Basics</strong></p>
<p><a href="http://www.ruchitsurati.net/myfiles/Prez-Office2003.zip" target="_blank">Download Office 2003 Format</a></p>
<p><a href="http://www.ruchitsurati.net/myfiles/Prez-Office2007.zip" target="_blank">Download Office 2007 Format (preferable)</a></p>
<p>&#160;</p>
<p>Ruchit S.    </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2008/04/23/my-presentations-at-tops-int-on-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

