<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Tranxition Developer Blog &#187; C#</title>
	<atom:link href="http://tranxcoder.wordpress.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://tranxcoder.wordpress.com</link>
	<description>Random musings from the developers at Tranxition</description>
	<lastBuildDate>Tue, 24 Mar 2009 18:14:16 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='tranxcoder.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/a141c5ce8e6e7831514f7c306752642f?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>The Tranxition Developer Blog &#187; C#</title>
		<link>http://tranxcoder.wordpress.com</link>
	</image>
			<item>
		<title>Disposable C# Snippets</title>
		<link>http://tranxcoder.wordpress.com/2008/07/17/disposable-c-snippets/</link>
		<comments>http://tranxcoder.wordpress.com/2008/07/17/disposable-c-snippets/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 20:16:31 +0000</pubDate>
		<dc:creator>cgassib</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://tranxcoder.wordpress.com/2008/07/17/disposable-c-snippets/</guid>
		<description><![CDATA[Visual Studio code snippets were brought up a couple times today.&#160; Which reminded me of the only two snippets I&#8217;ve ever written and used.&#160; I think they&#8217;re useful to save me some typing.&#160; In C# whenever you have some class that is holding onto unmanaged resources, or even a lot of managed resources, you really [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tranxcoder.wordpress.com&blog=3688975&post=61&subd=tranxcoder&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Visual Studio code snippets were brought up a couple times today.&nbsp; Which reminded me of the only two snippets I&#8217;ve ever written and used.&nbsp; I think they&#8217;re useful to save me some typing.&nbsp; In C# whenever you have some class that is holding onto unmanaged resources, or even a lot of managed resources, you really need to make it IDisposable.&nbsp; The problem is it&#8217;s a fair amount of repetitive typing to get there.&nbsp; </p>
<p><span id="more-61"></span>
</p>
<p>I have two versions: one for a base class and one for a derived class.&nbsp; You use the Base Dispose Pattern snippet if your class is the first class in your hierarchy that implements IDisposable.&nbsp; You use the Derived Dispose Pattern snippet if your class is derived from another class that implements IDisposable.&nbsp; Just put your caret on a line within class scope, but outside method scope.&nbsp; Hit the old &#8220;Ctrl K X&#8221;, select &#8220;My Code Snippets&#8221; from the context menu, then find the correct Dispose Pattern.&nbsp; Don&#8217;t forget to add IDisposable to your class definition if it&#8217;s a base disposable class.</p>
<p>After the snippet is pasted you&#8217;ll have a couple sections to fill in.&nbsp; The fill in sections are marked with comments.&nbsp; The managed section is where you clean up your managed member data.&nbsp; You would do this by calling Dispose() on IDisposable types and breaking references by setting them to null.&nbsp; This makes it easier for the garbage collector to know what to clean up.&nbsp; For example:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:green;">// if x is a disposable type:</span></p>
<p style="margin:0;"><span style="color:blue;">if</span> (x != <span style="color:blue;">null</span>)</p>
<p style="margin:0;">{</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; x.Dispose();</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; x = <span style="color:blue;">null</span>;</p>
<p style="margin:0;">}</p>
<p style="margin:0;">&nbsp;</p>
<p style="margin:0;"><span style="color:green;">// if x is not a disposable reference type:</span></p>
<p style="margin:0;">x = <span style="color:blue;">null</span>;</p>
</div>
<p>The unmanaged section is where you would clean up any native resources used by your class.&nbsp; For example: you would close any open win32 handles there.</p>
<p>The disposed member variable can be used in debugging to find out if your object is being referenced after it&#8217;s been disposed.&nbsp; This is a bad thing, but you can quickly check for it by using code like the following:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:blue;">public</span> <span style="color:blue;">void</span> MyMethod()</p>
<p style="margin:0;">{</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; <span style="color:blue;">if</span> (disposed)</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:blue;">throw</span> <span style="color:blue;">new</span> ObjectDisposedException(<span style="color:#a31515;">&#8220;MyClass.MyMethod() called on disposed object!&#8221;</span>);</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; <span style="color:green;">// TODO: write method code.</span></p>
<p style="margin:0;">}</p>
</div>
<p>Copy these two files into your DocumentsVisual Studio 2008Code SnippetsVisual C#My Code Snippets folder:</p>
<p>Base Dispose Pattern.snippet:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:blue;">&lt;?</span><span style="color:#a31515;">xml</span><span style="color:blue;"> </span><span style="color:red;">version</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">1.0</span>&#8220;<span style="color:blue;"> </span><span style="color:red;">encoding</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">utf-8</span>&#8220;<span style="color:blue;">?&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&lt;</span><span style="color:#a31515;">CodeSnippets</span><span style="color:blue;"> </span><span style="color:red;">xmlns</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp; &lt;</span><span style="color:#a31515;">CodeSnippet</span><span style="color:blue;"> </span><span style="color:red;">Format</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">1.0.0</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Header</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Title</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Base Dispose Pattern</p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Title</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Header</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Snippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Declarations</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Literal</span><span style="color:blue;"> </span><span style="color:red;">Editable</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">false</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">ID</span><span style="color:blue;">&gt;</span>classname<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ID</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">ToolTip</span><span style="color:blue;">&gt;</span>The name of this class.<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ToolTip</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Default</span><span style="color:blue;">&gt;</span>BaseResource<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Default</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Function</span><span style="color:blue;">&gt;</span>ClassName()<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Function</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Literal</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Declarations</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Code</span><span style="color:blue;"> </span><span style="color:red;">Language</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">CSharp</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;![CDATA[</span><span style="color:gray;">private bool disposed = false;</span></p>
<p style="margin:0;">&nbsp;</p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Dispose()</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Dispose(true);</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GC.SuppressFinalize(this);</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;">&nbsp;</p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected virtual void Dispose(bool disposing)</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!disposed)</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (disposing) // Managed:</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Unmanaged:</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; disposed = true;</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;">&nbsp;</p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ~$classname$()</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Dispose(false);</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span><span style="color:blue;">]]&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Code</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Snippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp; &lt;/</span><span style="color:#a31515;">CodeSnippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&lt;/</span><span style="color:#a31515;">CodeSnippets</span><span style="color:blue;">&gt;</span></p>
</div>
<p>Derived Dispose Pattern.snippet:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:blue;">&lt;?</span><span style="color:#a31515;">xml</span><span style="color:blue;"> </span><span style="color:red;">version</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">1.0</span>&#8220;<span style="color:blue;"> </span><span style="color:red;">encoding</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">utf-8</span>&#8220;<span style="color:blue;">?&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&lt;</span><span style="color:#a31515;">CodeSnippets</span><span style="color:blue;"> </span><span style="color:red;">xmlns</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp; &lt;</span><span style="color:#a31515;">CodeSnippet</span><span style="color:blue;"> </span><span style="color:red;">Format</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">1.0.0</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Header</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Title</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Derived Dispose Pattern</p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Title</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Header</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Snippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span><span style="color:#a31515;">Code</span><span style="color:blue;"> </span><span style="color:red;">Language</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">CSharp</span>&#8220;<span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;![CDATA[</span><span style="color:gray;">private bool disposed = false;</span></p>
<p style="margin:0;">&nbsp;</p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void Dispose(bool disposing)</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!disposed)</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (disposing) // Managed:</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Unmanaged:</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; disposed = true;</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; finally</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.Dispose(disposing);</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></p>
<p style="margin:0;"><span style="color:gray;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span><span style="color:blue;">]]&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Code</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp;&nbsp;&nbsp; &lt;/</span><span style="color:#a31515;">Snippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&nbsp; &lt;/</span><span style="color:#a31515;">CodeSnippet</span><span style="color:blue;">&gt;</span></p>
<p style="margin:0;"><span style="color:blue;">&lt;/</span><span style="color:#a31515;">CodeSnippets</span><span style="color:blue;">&gt;</span></p>
</div>
<p>Enjoy!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tranxcoder.wordpress.com/61/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tranxcoder.wordpress.com/61/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tranxcoder.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tranxcoder.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tranxcoder.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tranxcoder.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tranxcoder.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tranxcoder.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tranxcoder.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tranxcoder.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tranxcoder.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tranxcoder.wordpress.com/61/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tranxcoder.wordpress.com&blog=3688975&post=61&subd=tranxcoder&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tranxcoder.wordpress.com/2008/07/17/disposable-c-snippets/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">cgassib</media:title>
		</media:content>
	</item>
		<item>
		<title>A Generic Factory in C#</title>
		<link>http://tranxcoder.wordpress.com/2008/07/11/a-generic-factory-in-c/</link>
		<comments>http://tranxcoder.wordpress.com/2008/07/11/a-generic-factory-in-c/#comments</comments>
		<pubDate>Fri, 11 Jul 2008 22:32:26 +0000</pubDate>
		<dc:creator>cgassib</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://tranxcoder.wordpress.com/2008/07/11/a-generic-factory-in-c/</guid>
		<description><![CDATA[There is this really popular OOP design pattern that we at Tranxition, and other developers elsewhere, use frequently.  Years ago, after reading about the factory pattern in the GOF book I immediately thought of some possible uses for it in my work.  I was really excited to code it up&#8230; the first time.  After having [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tranxcoder.wordpress.com&blog=3688975&post=57&subd=tranxcoder&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>There is this really popular OOP design pattern that we at Tranxition, and other developers elsewhere, use frequently.  Years ago, after reading about the factory pattern in the GOF book I immediately thought of some possible uses for it in my work.  I was really excited to code it up&#8230; the first time.  After having writing the code for one factory though, it was clear to me it should just be a library and there were some things overlooked by most example implementations.</p>
<p><span id="more-57"></span>Here&#8217;s a classic example from a simple drawing program:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ShapeFactory</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Shape</span> CreateObject(<span style="color:#2b91af;">ShapeName</span> shapeName)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">switch</span> (shapeName)</p>
<p style="margin:0;">        {</p>
<p style="margin:0;">            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">ShapeName</span>.Circle:</p>
<p style="margin:0;">                <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Circle</span>();</p>
<p style="margin:0;">            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">ShapeName</span>.Square:</p>
<p style="margin:0;">                <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Square</span>();</p>
<p style="margin:0;">            <span style="color:#0000ff;">default</span>:</p>
<p style="margin:0;">                <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Exception</span>(<span style="color:#a31515;">&#8220;unknown shape type&#8221;</span>);</p>
<p style="margin:0;">        }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>The solution this ShapeFactory provides is pretty cool actually.  Now, if you need to add a new shape to the screen you just call one function.  Most of your code doesn&#8217;t have to know the details of the shape the user wants to create.  You just call the CreateObject() method passing the shape&#8217;s name and you get back a reference to generic shape object that can be stored in any shape container.  The shape container gets passed along and presumably gets a virtual Shape.Draw() method called on all of its contents in a foreach loop.</p>
<p>That&#8217;s really awesome until you want to add Triangles to your drawing program.  You probably start by adding a new Triangle.cs class file to your project.  Nice and OOP-y so far.  But then you have to crack open the ShapeName enumeration to add a new identifier for your Triangle class.  Next you have to crack open the switch statement of your ShapeFactory.CreateObject() method to add a case for your new Triangle class.  That&#8217;s two violations of the <a href="http://en.wikipedia.org/wiki/Open_Closed_Principle">open/closed principle</a>.  That&#8217;s not so awesome.  I like making as few changes as possible to existing code when adding features.<br />
You&#8217;ll notice that the switch statement is really switching on a type.  That sounds familiar, like I&#8217;ve heard that idea before somewhere&#8230;  It&#8217;s too bad we don&#8217;t have virtual constructors, but in the meantime: you could add some static factory methods to the derived Shape classes.  Then, you could replace that switch statement with a map from ShapeNames to ShapeFactory Methods.  You would end up with something like this:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">delegate</span> <span style="color:#2b91af;">Shape</span> <span style="color:#2b91af;">ShapeFactoryMethod</span>();</p>
<p style="margin:0;"> </p>
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Circle</span> : <span style="color:#2b91af;">Shape</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Shape</span> CreateObject()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Circle</span>();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
<p style="margin:0;"> </p>
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Square</span> : <span style="color:#2b91af;">Shape</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Shape</span> CreateObject()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Square</span>();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
<p style="margin:0;"> </p>
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ShapeFactory</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">private</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">ShapeName</span>, <span style="color:#2b91af;">ShapeFactoryMethod</span>&gt; map = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">ShapeName</span>, <span style="color:#2b91af;">ShapeFactoryMethod</span>&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Shape</span> CreateObject(<span style="color:#2b91af;">ShapeName</span> shapeName)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> map[shapeName]();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> Register(<span style="color:#2b91af;">ShapeName</span> shapeName, <span style="color:#2b91af;">ShapeFactoryMethod</span> shapeFactoryMethod)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        map.Add(shapeName, shapeFactoryMethod);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">bool</span> Unregister(<span style="color:#2b91af;">ShapeName</span> shapeName)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> map.Remove(shapeName);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>That&#8217;s pretty cool, we got rid of the switch statement.  Now you don&#8217;t have to crack open the ShapeFactory.cs file for every additional shape you add, but somewhere you still need to instantiate a ShapeFactory and populate its map with shapes types.  We haven&#8217;t solved the problem yet, just moved it:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Program</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">ShapeFactory</span> shapeFactory = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">ShapeFactory</span>();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> CreateShapeFactory()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        shapeFactory.Register(<span style="color:#2b91af;">ShapeName</span>.Circle, <span style="color:#2b91af;">Circle</span>.CreateObject);</p>
<p style="margin:0;">        shapeFactory.Register(<span style="color:#2b91af;">ShapeName</span>.Square, <span style="color:#2b91af;">Square</span>.CreateObject);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>We still have two places to change every time we want to add another shape type.  It would be really nice if we could just add a static constructor to each class derived Shape that would automatically register itself with a static ShapeFactory like this:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Circle</span> : <span style="color:#2b91af;">Shape</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">static</span> Circle()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">ShapeFactory</span>.Register(<span style="color:#2b91af;">ShapeName</span>.Circle, <span style="color:#2b91af;">Circle</span>.CreateObject);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Shape</span> CreateObject()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Circle</span>();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>Unfortunately .NET doesn&#8217;t play that way.  A class&#8217;s Static constructor is not called until the first time a method of that class is called.  To my knowledge, there is nothing in C# that is equivalent to the static scope initialization of C++.  However, there is something C# has that may still be useful: reflection.  In preparation, let&#8217;s add a little searchable identifier to each class that&#8217;s derived from shape.  Like this:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Circle</span> : <span style="color:#2b91af;">Shape</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">ShapeName</span> ShapeName</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> <span style="color:#2b91af;">ShapeName</span>.Circle; }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Shape</span> CreateObject()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Circle</span>();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>Now let&#8217;s use a little reflection in the ShapeFactory to automatically load up its map:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ShapeFactory</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">private</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">ShapeName</span>, ShapeFactoryMethod&gt; map = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">ShapeName</span>, ShapeFactoryMethod&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> ShapeFactory()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">Type</span>[] shapeTypes = <span style="color:#2b91af;">Assembly</span>.GetAssembly(<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)).GetTypes();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">        <span style="color:#0000ff;">foreach</span> (<span style="color:#2b91af;">Type</span> shapeType <span style="color:#0000ff;">in</span> shapeTypes)</p>
<p style="margin:0;">        {</p>
<p style="margin:0;">            <span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>).IsAssignableFrom(shapeType) || shapeType == <span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)) <span style="color:#008000;">// if (shapeType is not derived from Shape)</span></p>
<p style="margin:0;">            {</p>
<p style="margin:0;">                <span style="color:#0000ff;">continue</span>; <span style="color:#008000;">// this type isn&#8217;t a Shape type, keep searching through the the assembly</span></p>
<p style="margin:0;">            }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Get the name of the shape type.</span></p>
<p style="margin:0;">            <span style="color:#2b91af;">PropertyInfo</span> propertyInfo = shapeType.GetProperty(<span style="color:#a31515;">&#8220;ShapeName&#8221;</span>);</p>
<p style="margin:0;">            <span style="color:#2b91af;">Debug</span>.Assert(propertyInfo != <span style="color:#0000ff;">null</span>, <span style="color:#a31515;">&#8220;ShapeName property not implemented for shape type: &#8220;</span> + shapeType.Name);</p>
<p style="margin:0;">            <span style="color:#2b91af;">ShapeName</span> shapeName = (<span style="color:#2b91af;">ShapeName</span>)propertyInfo.GetValue(<span style="color:#0000ff;">null</span>, <span style="color:#0000ff;">null</span>); <span style="color:#008000;">// shapeName = shapeType.ShapeName;</span></p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Get the static factory method of the shape type.</span></p>
<p style="margin:0;">            <span style="color:#2b91af;">MethodInfo</span> methodInfo = shapeType.GetMethod(<span style="color:#a31515;">&#8220;CreateObject&#8221;</span>);</p>
<p style="margin:0;">            <span style="color:#2b91af;">Debug</span>.Assert(methodInfo != <span style="color:#0000ff;">null</span>, <span style="color:#a31515;">&#8220;Factory method not implemented for shape type: &#8220;</span> + shapeType.Name);</p>
<p style="margin:0;">            <span style="color:#2b91af;">Delegate</span> shapeFactoryMethod = <span style="color:#2b91af;">Delegate</span>.CreateDelegate(<span style="color:#0000ff;">typeof</span>(ShapeFactoryMethod), methodInfo);</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Automatically register the shape type.</span></p>
<p style="margin:0;">            map.Add(shapeName, (ShapeFactoryMethod)shapeFactoryMethod);</p>
<p style="margin:0;">        }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Shape</span> CreateObject(<span style="color:#2b91af;">ShapeName</span> shapeName)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> map[shapeName]();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>We just got rid of the need to manually maintain the ShapeFactory&#8217;s list of shapes.  Pretty cool so far.  Now, what about that enumeration?  Let&#8217;s throw a little more reflection code at the problem:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ShapeFactory</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">private</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, ShapeFactoryMethod&gt; map = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, ShapeFactoryMethod&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> ShapeFactory()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">Type</span>[] shapeTypes = <span style="color:#2b91af;">Assembly</span>.GetAssembly(<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)).GetTypes();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">        <span style="color:#0000ff;">foreach</span> (<span style="color:#2b91af;">Type</span> shapeType <span style="color:#0000ff;">in</span> shapeTypes)</p>
<p style="margin:0;">        {</p>
<p style="margin:0;">            <span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>).IsAssignableFrom(shapeType) || shapeType == <span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)) <span style="color:#008000;">// if (shapeType is not derived from Shape)</span></p>
<p style="margin:0;">            {</p>
<p style="margin:0;">                <span style="color:#0000ff;">continue</span>; <span style="color:#008000;">// this type isn&#8217;t a Shape type, keep searching through the the assembly</span></p>
<p style="margin:0;">            }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Get the static factory method of the shape type.</span></p>
<p style="margin:0;">            <span style="color:#2b91af;">MethodInfo</span> methodInfo = shapeType.GetMethod(<span style="color:#a31515;">&#8220;CreateObject&#8221;</span>);</p>
<p style="margin:0;">            <span style="color:#2b91af;">Debug</span>.Assert(methodInfo != <span style="color:#0000ff;">null</span>, <span style="color:#a31515;">&#8220;Factory method not implemented for shape type: &#8220;</span> + shapeType.Name);</p>
<p style="margin:0;">            <span style="color:#2b91af;">Delegate</span> shapeFactoryMethod = <span style="color:#2b91af;">Delegate</span>.CreateDelegate(<span style="color:#0000ff;">typeof</span>(ShapeFactoryMethod), methodInfo);</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Automatically register the shape type.</span></p>
<p style="margin:0;">            map.Add(shapeType.Name, (ShapeFactoryMethod)shapeFactoryMethod);</p>
<p style="margin:0;">        }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Shape</span> CreateObject(<span style="color:#0000ff;">string</span> shapeName)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> map[shapeName]();</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>So the enumeration is gone AND you can even ditch the ShapeName property attached to each Shape class.  Now, if you want to add a Triangle class all you need to do is drop in your Triangle.cs source file and you won&#8217;t have need to modified existing code.  Sweet!  The only thing you have to remember to do is include a CreateObject() method on each new shape.  But wait!  Reflection can help us here too:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ShapeFactory</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">private</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, <span style="color:#2b91af;">Type</span>&gt; map = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, <span style="color:#2b91af;">Type</span>&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> ShapeFactory()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">Type</span>[] shapeTypes = <span style="color:#2b91af;">Assembly</span>.GetAssembly(<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)).GetTypes();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">        <span style="color:#0000ff;">foreach</span> (<span style="color:#2b91af;">Type</span> shapeType <span style="color:#0000ff;">in</span> shapeTypes)</p>
<p style="margin:0;">        {</p>
<p style="margin:0;">            <span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>).IsAssignableFrom(shapeType) || shapeType == <span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Shape</span>)) <span style="color:#008000;">// if (shapeType is not derived from Shape)</span></p>
<p style="margin:0;">            {</p>
<p style="margin:0;">                <span style="color:#0000ff;">continue</span>; <span style="color:#008000;">// this type isn&#8217;t a Shape type, keep searching through the the assembly</span></p>
<p style="margin:0;">            }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Automatically register the shape type.</span></p>
<p style="margin:0;">            map.Add(shapeType.Name, shapeType);</p>
<p style="margin:0;">        }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Shape</span> CreateObject(<span style="color:#0000ff;">string</span> shapeName, <span style="color:#0000ff;">params</span> <span style="color:#0000ff;">object</span>[] args)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> (<span style="color:#2b91af;">Shape</span>)<span style="color:#2b91af;">Activator</span>.CreateInstance(map[shapeName], args);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>Now we don&#8217;t have any special requirements of new Shape classes, we&#8217;ve ditched the extra factory method delegate, AND we can even use the most appropriate constructor for each object.  The only left to do is turn this factory into a library that works on any class hierarchy.  Let&#8217;s make it generic:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Factory</span>&lt;Product&gt;</p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">private</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, <span style="color:#2b91af;">Type</span>&gt; map = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#0000ff;">string</span>, <span style="color:#2b91af;">Type</span>&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> Factory()</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">Type</span>[] types = <span style="color:#2b91af;">Assembly</span>.GetAssembly(<span style="color:#0000ff;">typeof</span>(Product)).GetTypes();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">        <span style="color:#0000ff;">foreach</span> (<span style="color:#2b91af;">Type</span> type <span style="color:#0000ff;">in</span> types)</p>
<p style="margin:0;">        {</p>
<p style="margin:0;">            <span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">typeof</span>(Product).IsAssignableFrom(type) || type == <span style="color:#0000ff;">typeof</span>(Product)) <span style="color:#008000;">// if (type is not derived from Product)</span></p>
<p style="margin:0;">            {</p>
<p style="margin:0;">                <span style="color:#0000ff;">continue</span>; <span style="color:#008000;">// this type isn&#8217;t a Product type, keep searching through the the assembly</span></p>
<p style="margin:0;">            }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">            <span style="color:#008000;">// Automatically register the Product type.</span></p>
<p style="margin:0;">            map.Add(type.Name, type);</p>
<p style="margin:0;">        }</p>
<p style="margin:0;">    }</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">public</span> Product CreateObject(<span style="color:#0000ff;">string</span> productName, <span style="color:#0000ff;">params</span> <span style="color:#0000ff;">object</span>[] args)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#0000ff;">return</span> (Product)<span style="color:#2b91af;">Activator</span>.CreateInstance(map[productName], args);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>And this is how we&#8217;d use it as a Shape factory:</p>
<div style="font-size:10pt;background:white;color:black;font-family:courier new;">
<p style="margin:0;"><span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Program</span></p>
<p style="margin:0;">{</p>
<p style="margin:0;">    <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Factory</span>&lt;<span style="color:#2b91af;">Shape</span>&gt; shapeFactory = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Factory</span>&lt;<span style="color:#2b91af;">Shape</span>&gt;();</p>
<p style="margin:0;"> </p>
<p style="margin:0;">    <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main(<span style="color:#0000ff;">string</span>[] args)</p>
<p style="margin:0;">    {</p>
<p style="margin:0;">        <span style="color:#2b91af;">Shape</span> s1 = shapeFactory.CreateObject(<span style="color:#a31515;">&#8220;Circle&#8221;</span>);</p>
<p style="margin:0;">        <span style="color:#2b91af;">Shape</span> s2 = shapeFactory.CreateObject(<span style="color:#a31515;">&#8220;Square&#8221;</span>);</p>
<p style="margin:0;">    }</p>
<p style="margin:0;">}</p>
</div>
<p>Now you&#8217;ve got a generic factory library in C# &#8230;and there&#8217;s still plenty of room to trick it out in my next blog post.  In the meantime, you are probably aware that the factory pattern is commonly combined with the singleton pattern.  I would personally recommend this article on the subject: <a href="http://www.yoda.arachsys.com/csharp/singleton.html">http://www.yoda.arachsys.com/csharp/singleton.html</a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tranxcoder.wordpress.com/57/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tranxcoder.wordpress.com/57/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tranxcoder.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tranxcoder.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tranxcoder.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tranxcoder.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tranxcoder.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tranxcoder.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tranxcoder.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tranxcoder.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tranxcoder.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tranxcoder.wordpress.com/57/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tranxcoder.wordpress.com&blog=3688975&post=57&subd=tranxcoder&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tranxcoder.wordpress.com/2008/07/11/a-generic-factory-in-c/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">cgassib</media:title>
		</media:content>
	</item>
	</channel>
</rss>