<?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>.Net Smoothie &#187; C# 2.0</title>
	<atom:link href="http://www.richardbushnell.net/category/c-2-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.richardbushnell.net</link>
	<description></description>
	<lastBuildDate>Wed, 30 Dec 2009 11:42:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Refactoring C# Series: Aggregation of IEnumerable</title>
		<link>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/</link>
		<comments>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/#comments</comments>
		<pubDate>Sun, 02 Mar 2008 20:54:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Accumulator]]></category>
		<category><![CDATA[Aggregate]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/</guid>
		<description><![CDATA[I was recently reading Programming Ruby: The Pragmatic Programmers&#8217; Guide, Second Edition, and came across this piece of example Ruby code: [1,3,5,7].inject(0) {&#124;sum, element&#124; sum+element} -&#62; 16 [1,3,5,7].inject(1) {&#124;product, element&#124; product*element} -&#62; 105 Inject is a method which acts on an array by aggregating or accumulating the values within that array. It loops through the [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F02%2Frefactoring-c-series-aggregation-of-ienumerable%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p><a href="http://www.amazon.com/gp/product/0974514055?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0974514055"><img style="margin: 0px 20px 20px 0px" src="/images/21VJS5BMKVL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0974514055" width="1" border="0" /></p>
<p>I was recently reading <a href="http://www.amazon.com/gp/product/0974514055?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0974514055">Programming Ruby: The Pragmatic Programmers&#8217; Guide, Second Edition</a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0974514055" width="1" border="0" />, and came across this piece of example Ruby code:</p>
<blockquote><p>[1,3,5,7].inject(0) {|sum, element| sum+element} -&gt; 16      <br />[1,3,5,7].inject(1) {|product, element| product*element} -&gt; 105</p>
</blockquote>
<p><strong>Inject</strong> is a method which acts on an array by <em>aggregating</em> or <em>accumulating</em> the values within that array. It loops through the array, and for every item in the array, it performs a function. It then saves the result for the next iteration of the loop and eventually returns the aggregated value.</p>
<p>In <strong>C# 1.0</strong> you would probably write such a method like this:</p>
<pre class="code"><span style="color: blue">int </span>sum = 0;
<span style="color: blue">int</span>[] list = <span style="color: blue">new int</span>[] { 1, 3, 5, 7 };
<span style="color: blue">foreach </span>(<span style="color: blue">int </span>item <span style="color: blue">in </span>list)
{
  <span style="color: green">// Perform some function, then save the result
  </span>sum = sum + item;
}</pre>
<p>It&#8217;s a bit long-winded, and if you wanted to make it reusable, you&#8217;d have a hard time.</p>
<p>In C# 3.0, you can do it just like you can in Ruby.</p>
<p><span id="more-60"></span></p>
<h2>Defining the Aggregation</h2>
<p>First, let me explain how the Ruby <strong>inject </strong>method works.</p>
<p>First of all, it&#8217;s really misnamed in Ruby. The method is an aggregator, or even an &quot;accumulator&quot;. It aggregates or accumulates values. It takes two parameters &#8211; a starter value, and a block. In C# 3.0 we basically call a block a delegate, although in this case, it&#8217;s more like a Lambda Expression.</p>
<p>The <strong>inject</strong> method works like this:</p>
<ol>
<li>it takes the starter parameter and sets the aggregated value (the <strong>sum</strong> in the above example) to its value. </li>
<li>For the first item in the array, it passes the tarter value and the item itself to the block, which then performs the defined function on it. </li>
<li>The return value from the block is then assigned to the running aggregated value. </li>
<li>The running aggregated value is passed into the next iteration with the next item from the list. The function is called on those items again. </li>
<li>When the method has iterated over all items in the list, it returns the aggregated value. </li>
</ol>
<h2>Moving to C# 2.0</h2>
<p>So, let&#8217;s imagine you were trying to write the <strong>Inject </strong>method in <strong>C# 2.0</strong>. If you were to refactor the above <strong>C# 1.0</strong> example as <strong>C# 2.0</strong>, you might use anonymous methods to write this:</p>
<pre class="code"><span style="color: green">// Define a delegate
</span><span style="color: blue">delegate int </span><span style="color: #2b91af">Aggregator</span>(<span style="color: blue">int </span>sum, <span style="color: blue">int </span>item);

<span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args) {

  <span style="color: blue">int </span>sum = 0;
  <span style="color: blue">int</span>[] list = <span style="color: blue">new int</span>[] { 1, 3, 5, 7 };

  sum = Inject(sum, list,     <span style="color: blue">delegate</span>(<span style="color: blue">int </span>starterVal, <span style="color: blue">int </span>item) {
      <span style="color: blue">return </span>starterVal + item;
    });
}

<span style="color: blue">int </span>Inject(<span style="color: blue">int </span>starterVal, <span style="color: blue">int</span>[] list,
           <span style="color: #2b91af">Aggregator </span>aggregator) {
  <span style="color: blue">int </span>sum = starterVal;
  <span style="color: blue">foreach </span>(<span style="color: blue">int </span>item <span style="color: blue">in </span>list) {
    <span style="color: green">// Perform some function, then save the result
    </span>sum = aggregator(sum, item);
  }
  <span style="color: blue">return </span>sum;</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>However, that would only work for <strong>int</strong> objects. You could really make it generic, and use the same method for other types:</p>
<pre class="code"><span style="color: green">// Define a delegate
</span><span style="color: blue">delegate </span>T <span style="color: #2b91af">Aggregator</span>&lt;T&gt;(T sum, T item);

<span style="color: blue">...</span></pre>
<p>
  </p>
<pre class="code"><span style="color: blue"></span>  sum = Inject&lt;<span style="color: blue">int</span>&gt;(sum, list,
     <span style="color: blue">delegate</span>(<span style="color: blue">int </span>starterVal, <span style="color: blue">int </span>item) {
      <span style="color: blue">return </span>starterVal + item;
    });</pre>
<p>
  </p>
<pre class="code">...

T Inject&lt;T&gt;(T starterVal, T[] list,
  <span style="color: #2b91af">Aggregator</span>&lt;T&gt; aggregator) {
  T sum = starterVal;
  <span style="color: blue">foreach </span>(T item <span style="color: blue">in </span>list) {
    <span style="color: green">// Perform some function, then save the result
    </span>sum = aggregator(sum, item);
  }
  <span style="color: blue">return </span>sum;
}</pre>
<p>It&#8217;s nicer, but the Ruby method still wins hands-down for neatness.</p>
<h2>Move Over Ruby, Here Comes C# 3.0</h2>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The good news is, the C# 3.0 compiler and the .Net 3.5 framework can now take care of most of this for you.</p>
<p>To start with, the Aggregator delegate is no longer necessary, because the new <strong>Func&lt;T,T,T&gt;</strong> delegate already defines a generic delegate which returns a value.</p>
<pre class="code">T Inject&lt;T&gt;(T starterVal, T[] list, <span style="color: #2b91af">Func</span>&lt;T,T,T&gt; aggregator)</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Secondly, the anonymous function using the delegate keyword can be replaced by a lambda expression like this:</p>
<pre class="code">(starterVal, item) =&gt; starterVal + item</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Thirdly, the Inject method can be defined as an extension method so that you can call it like this:</p>
<pre class="code">sum = list.Inject(sum, (starterVal, item) =&gt; starterVal + item );</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And fourthly, the compiler can infer the type for you, so you don&#8217;t need to specify it on calling the method.</p>
<h2>The Aggregate Method</h2>
<p>But the <em>even better news</em> is that this method is already defined in the .Net framework for you, so you don&#8217;t even have to write it. Instead of being called <strong>inject</strong>, it&#8217;s called <strong>Aggregate</strong>, and is defined on the <strong>System.Linq.Enumerable&lt;T&gt;</strong> class.</p>
<p>So basically, using C# 3.0, you could reduce the above code to this:</p>
<pre class="code"><span style="color: blue">var </span>sum = 0;
<span style="color: blue">var </span>list = <span style="color: blue">new</span>[] { 1, 3, 5, 7 };
sum = list.Aggregate(sum,
                     (starterVal, item) =&gt; starterVal + item );</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You get an extra bonus point if you spotted the extra C# 3.0 features I sneaked in there &#8211; the var keyword, and array initializers.</p>
<p>C# 3.0 is pretty neat huh? Move over Ruby.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F02%2Frefactoring-c-series-aggregation-of-ienumerable%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/02/refactoring-c-series-aggregation-of-ienumerable/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Writing Custom Exception Classes the Quick Way</title>
		<link>http://www.richardbushnell.net/2008/02/15/writing-custom-exception-classes-the-quick-way/</link>
		<comments>http://www.richardbushnell.net/2008/02/15/writing-custom-exception-classes-the-quick-way/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 16:00:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/15/writing-custom-exception-classes-the-quick-way/</guid>
		<description><![CDATA[Until recently I thought this was a well-known feature. After demonstrating it a few times, I found out it wasn&#8217;t. A long time ago, in an cubicle far, far away, someone created the .Net Framework. To cut a long story short, they simultaneously produced guidelines for creating Exception classes, which you should always use or [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F15%2Fwriting-custom-exception-classes-the-quick-way%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Until recently I thought this was a well-known feature. After demonstrating it a few times, I found out it wasn&#8217;t.</p>
<p>A long time ago, in an cubicle far, far away, someone created the .Net Framework. To cut a long story short, they simultaneously produced guidelines for creating Exception classes, which you should always use or face having your fingernails pulled out with a staple-gun.</p>
<p>The guidelines state:</p>
<blockquote>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 10pt; font-family: 'Arial','sans-serif'">&#8220;Use the common constructors shown in the following code example when creating exception classes. &#8220;<o:p></o:p></span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 10pt; font-family: 'Courier New'">[C#]<o:p></o:p></span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 10pt; color: blue; font-family: 'Courier New'">public</span><span style="font-size: 10pt; font-family: 'Courier New'"> <span style="color: blue">class</span> XxxException : ApplicationException<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'">{<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'"><span>   </span><span style="color: blue">public</span> XxxException() {&#8230; }<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'"><span>   </span><span style="color: blue">public</span> XxxException(<span style="color: blue">string</span> message) {&#8230; }<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'"><span>   </span><span style="color: blue">public</span> XxxException(<span style="color: blue">string</span> message, Exception inner) {&#8230; }<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'"><span>   </span><span style="color: blue">public</span> XxxException(SerializationInfo info, StreamingContext context) {&#8230;}<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'">}<o:p></o:p></span></p></blockquote>
<p><span id="more-53"></span><br />
If you don&#8217;t believe me, you can look here:</p>
<p><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp" title="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp</a></p>
<p>Now, I don&#8217;t know about you, but I can&#8217;t remember all that every time I create a custom exception class. Maybe that&#8217;s why the guidelines also state:</p>
<blockquote><p>In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself.</p></blockquote>
<p>But let&#8217;s ignore that. It&#8217;s not relevant.</p>
<p>So, <em>did you know</em> that there is a Visual Studio code snippet that does the work for you? Here&#8217;s how you use it.</p>
<ol>
<li>Create a new class.</li>
<li>inside the namespace definition of the new class, type
<pre class="code">Exception</pre>
<p><a href="http://11011.net/software/vspaste"></a></li>
<li>Press the tab key twice.</li>
</ol>
<p>You then get the following code, free of charge:</p>
<pre class="code">[<span style="color: blue">global</span>::System.<span style="color: #2b91af">Serializable</span>]
<span style="color: blue">public class </span><span style="color: #2b91af">MyException </span>: <span style="color: #2b91af">Exception </span>{
<span style="color: green">
  </span><span style="color: blue">public </span>MyException() { }
  <span style="color: blue">public </span>MyException(<span style="color: blue">string </span>message) : <span style="color: blue">base</span>(message) { }
  <span style="color: blue">public </span>MyException(<span style="color: blue">string </span>message, <span style="color: #2b91af">Exception </span>inner) : <span style="color: blue">base</span>(message, inner) { }
  <span style="color: blue">protected </span>MyException(
  System.Runtime.Serialization.<span style="color: #2b91af">SerializationInfo </span>info,
  System.Runtime.Serialization.<span style="color: #2b91af">StreamingContext </span>context)
    : <span style="color: blue">base</span>(info, context) { }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>What&#8217;s more, you get code snippet functionality which automatically changes the names of all the constructors when you change the name of the class.</p>
<p>I wonder what other code snippets are available. Do you know of any cool ones? What are your favorites?</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F15%2Fwriting-custom-exception-classes-the-quick-way%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/15/writing-custom-exception-classes-the-quick-way/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Refactoring C# Series: Use Automatic Property</title>
		<link>http://www.richardbushnell.net/2007/12/28/refactoring-c-sharp-series-use-automatic-property/</link>
		<comments>http://www.richardbushnell.net/2007/12/28/refactoring-c-sharp-series-use-automatic-property/#comments</comments>
		<pubDate>Thu, 27 Dec 2007 22:00:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# automatic properties refactoring]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2007/12/28/refactoring-c-sharp-series-use-automatic-property/</guid>
		<description><![CDATA[Name Use Automatic Property Summary You have a property in a class which just wraps a field of the same type, and simply returns or sets that field. private string _field1; public string Field1 { get { return _field1; } set { _field1 = value; } } Becomes: public string Field1 { get; set; } [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F28%2Frefactoring-c-sharp-series-use-automatic-property%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><h2>Name</h2>
<p>Use Automatic Property</p>
<h2>Summary</h2>
<p>You have a property in a class which just wraps a field of the same type, and simply returns or sets that field.</p>
<pre class="code"><span style="color: blue">private string </span>_field1;
<span style="color: blue">public string </span>Field1
{
  <span style="color: blue">get </span>{ <span style="color: blue">return </span>_field1; }
  <span style="color: blue">set </span>{ _field1 = <span style="color: blue">value</span>; }
}</pre>
<p>Becomes:</p>
<pre class="code"><span style="color: blue">public string </span>Field1 { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<h2>C# Version</h2>
<p>3.0</p>
<h2>Motivation</h2>
<p>Encapsulation is quite possibly <em>the</em> key principle of object-oriented design. It is common practice in C# to encapsulate fields by wrapping them in a property. </p>
<p>When a class has many properties, much of the class is taken up by the same coding pattern for a property:</p>
<pre class="code"><span style="color: blue">private string </span>_field1;
<span style="color: blue">public string </span>Field1
{
  <span style="color: blue">get </span>{ <span style="color: blue">return </span>_field1; }
  <span style="color: blue">set </span>{ _field1 = <span style="color: blue">value</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In C# 3.0 this block of code can be removed by using automatic properties. The compiler will do the same thing that you would have done before if you just define the property name and the getter and setter.</p>
<pre class="code"><span style="color: blue">public string </span>Field1 { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Reducing the property code like this makes it much easier to understand the code later, as only the necessary details are defined. Even if you use a terse syntax formatting, as in the previous example, you are saving 5 lines of code per property. The way I usually format my code with extra linefeeds, I save 9 lines for each one. When there are a lot of properties in a class, that is a large amount of code which can be removed.</p>
<p>Removing code isn&#8217;t just good for making it easier to understand; it makes it easier to test too. You wouldn&#8217;t have to test properties to see if they are simply setting and getting the correct values with this syntax, as the compiler is doing the work for you. So if you have unit tests, you might be able to remove lots of property testing code.</p>
<p>Of course, if the property does not just simply set or get a field value, you must use the previous C# 1.0 syntax for properties. In addition, you cannot specify get or set alone, but you can include scope identifiers to make a set private, for example:</p>
<pre class="code"><span style="color: green">// The following are not valid:
// Automatically implemented properties must define both get and set accessors
</span><span style="color: blue">public string </span>GetOnly { <span style="color: blue">get</span>; } <span style="color: green">// Not valid
</span><span style="color: blue">public string </span>SetOnly { <span style="color: blue">set</span>; } <span style="color: green">// Not valid either

// But this is okay
</span><span style="color: blue">public string </span>GetWithPrivateSet { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h2><a href="http://11011.net/software/vspaste"></a>Mechanics</h2>
<ul>
<li>Remove the body of the property, replacing the code between the get and set blocks with a semicolon &#8220;;&#8221; .
<li>Compile.
<li>If there is a compiler warning that the field is no longer being used, you can now simply remove the field which the property was wrapping.
<li>If there is no compiler warning, other methods or properties are using the field directly. You can remove the field and recompile anyway, which will give you the location in the code where the field is being used. Replace each reference with a reference to the property instead.
<li>Compile. </li>
</ul>
<p>Repeat for each property.</p>
<p>If the field was a protected field, not private, then you might have subclasses which access the field. They will have to be changed to access the property instead of directly accessing the field.</p>
<p><strong>Tip</strong>: For new code, you can simply use the code snippet &#8220;prop&#8221; in Visual Studio 2008 to get an automatic property.</p>
<h2>Examples</h2>
<p>I&#8217;ll just do an example with one property, even though it looks a lot better with a longer class.</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Account
</span>{
  <span style="color: blue">private long </span>_id;
  <span style="color: blue">public long </span>ID
  {
    <span style="color: blue">get </span>{ <span style="color: blue">return </span>_id; }
    <span style="color: blue">set </span>{ _id = <span style="color: blue">value</span>; }
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>First, remove the body of the property getter and setter (and apply a bit of reformatting too, if you like):</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Account
</span>{
  <span style="color: blue">private long </span>_id;
  <span style="color: blue">public long </span>ID { <span style="color: blue">get </span>; <span style="color: blue">set </span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Compile, to make sure the code is happy, then remove the field:</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Account
</span>{
  <span style="color: blue">public long </span>ID { <span style="color: blue">get </span>; <span style="color: blue">set </span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F28%2Frefactoring-c-sharp-series-use-automatic-property%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2007/12/28/refactoring-c-sharp-series-use-automatic-property/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>New series: Refactoring C# 1.0 code to C# 3.0</title>
		<link>http://www.richardbushnell.net/2007/12/25/refactoring-c-10-code-to-c-30/</link>
		<comments>http://www.richardbushnell.net/2007/12/25/refactoring-c-10-code-to-c-30/#comments</comments>
		<pubDate>Tue, 25 Dec 2007 16:58:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 2.0]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# 3.0 migration upgrade refactor]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2007/12/25/refactoring-c-10-code-to-c-30/</guid>
		<description><![CDATA[I really like Scott Hanselmann&#8217;s idea to write an indefinite series of posts about reading code to be a better developer. I&#8217;m going to copy his idea, and write a series of my own. Since its first version, C# has evolved from being a Java clone to something much more dynamic. I&#8217;ve noticed that developers [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F25%2Frefactoring-c-10-code-to-c-30%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>I really like <a href="http://www.hanselman.com/blog/" target="_blank">Scott Hanselmann&#8217;s</a> idea to write an indefinite series of posts about <a href="http://www.hanselman.com/blog/ReadingToBeABetterDeveloperTheCoding4FunDevKit.aspx" target="_blank">reading code to be a better developer</a>. I&#8217;m going to copy his idea, and write a series of my own.</p>
<p>Since its first version, C# has evolved from being a Java clone to something much more dynamic. I&#8217;ve noticed that developers often find themselves stuck long projects, and its sometimes hard to keep up with all the changes. I know a lot of developers who are still using .Net 1.1 because the project they are working on forces them too. For them, C# is still very much like Java. </p>
<p>So for all those who want to know what has changed since the first version, I&#8217;ve decided to make a new series of posts called &#8220;Refactoring from C# 1.0 to C# 3.0&#8243;. I will show through examples how you can make your code easier to understand and maintain by using the new features in C#. I&#8217;m not necessarily going to do it in historical order &#8211; I won&#8217;t show any preference for C# 2.0 Generics over C# 3.0 Extension Methods, for example. And C# 2.0 anonymous methods will take second place to C# 3.0 lambda expressions, which generally replaces them. I&#8217;m going to try to show how things have changed, and when you should or should not use the new features.</p>
<p>Some of the things I&#8217;ll cover are:</p>
<ul>
<li>Anonymous types</li>
<li>Anonymous methods and lambda expressions</li>
<li>Extension Methods</li>
<li>Yield statements and iterators</li>
<li>Generics</li>
<li>List comprehensions (ala LINQ)</li>
<li>Mixins</li>
<li>Partial types</li>
<li>Type and Array inference</li>
<li>Property visibility</li>
<li>Automatic properties</li>
<li>Static classes</li>
<li>The Global namespace</li>
<li>Object, Collection and Dictionary initializers</li>
</ul>
<p>I&#8217;ll try to treat each one as a refactoring opportunity, and not as a &#8220;must&#8221; or &#8220;must-not&#8221;. The idea is to write more maintainable code using the new features, not just go along with the trends.</p>
<p><em>Note</em>: I&#8217;m not going to treat the .Net base library at all. Just the C# language.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F25%2Frefactoring-c-10-code-to-c-30%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2007/12/25/refactoring-c-10-code-to-c-30/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

