<?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>It&#039;s just code</title>
	<atom:link href="http://togaroga.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://togaroga.com/blog</link>
	<description>Andrew Hare&#039;s coding blog</description>
	<lastBuildDate>Tue, 05 Jan 2010 19:57:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Make aliases an option</title>
		<link>http://togaroga.com/blog/2009/11/make-aliases-an-option/</link>
		<comments>http://togaroga.com/blog/2009/11/make-aliases-an-option/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 02:42:04 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[visual-studio]]></category>

		<guid isPermaLink="false">http://togaroga.com/blog/?p=355</guid>
		<description><![CDATA[Do you prefer int or Int32?  How about string or String?  Some developers have strong preferences, others don&#8217;t care.  Personally, I prefer to use the actual CLR type names (in other words I prefer Int32 and String) and since I do, I feel as though I am a second-class citizen.

Interestingly enough, it [...]]]></description>
			<content:encoded><![CDATA[<p>Do you prefer <code>int</code> or <code>Int32</code>?  How about <code>string</code> or <code>String</code>?  Some developers have strong preferences, others don&#8217;t care.  Personally, I prefer to use the actual CLR type names (in other words I prefer <code>Int32</code> and <code>String</code>) and since I do, I feel as though I am a second-class citizen.</p>

<p>Interestingly enough, it is Visual Studio who makes me feel this way!  I am constantly frustrated when I use intellisense to auto-populate an object instantiation like this:</p>

<p><pre class="prettyprint">Dictionary&#60;String,Int32&#62; dictionary = new</pre></p>

<p>If I use intellisense to populate the remaining code I am left with this:</p>

<p><pre class="prettyprint">Dictionary&#60;String,Int32&#62; dictionary = new Dictionary&#60;string,int&#62;();</pre></p>

<p>This happens with any code that Visual Studio generates on my behalf: method overrides, method stubs, etc.  It would be really nice to be able to specify that I prefer to use the CLR type names over their C# aliases.  So I am making an official Visual Studio feature request:</p>

<blockquote>
  <p>Please allow us to specify whether or not suggested and generated code uses C# aliases or CLR type names.</p>
</blockquote>

<p>Those of us who care will greatly appreciate it.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/11/make-aliases-an-option/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Smarter type inference with C# 4</title>
		<link>http://togaroga.com/blog/2009/11/smarter-type-inference-with-c-4/</link>
		<comments>http://togaroga.com/blog/2009/11/smarter-type-inference-with-c-4/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 02:48:01 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[type-inference]]></category>

		<guid isPermaLink="false">http://togaroga.com/blog/?p=257</guid>
		<description><![CDATA[Here is a new addition to the C# language in version 4 that doesn&#8217;t seem to be getting much attention.  The type inference algorithm has become smarter and for the first time we are able to infer generic type arguments from the return types of methods in certain cases.

Consider this example that compiles in [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a new addition to the C# language in version 4 that doesn&#8217;t seem to be getting much attention.  The type inference algorithm has become smarter and for the first time we are able to infer generic type arguments from the return types of methods in certain cases.</p>

<p>Consider this example that compiles in C# 4 but does not compile in C# 3:</p>

<p><pre class="prettyprint">using System;
using System.Linq;<br />
class Example
{
    static void Main()
    {
        var characters 
            = new [] { 97, 98, 99 }
                .Select(Convert.ToChar);
    }
}</pre></p>

<p>Here I am converting an array of integers to a new sequence of characters.  In order to do this I chose to project this new sequence from the old sequence using LINQ&#8217;s <a href="http://msdn.microsoft.com/en-us/library/bb548891.aspx"><code>Enumerable.Select&lt;TSource,TResult&gt;</code></a> extension method.  Now if I were using C# 3 I would have to explicitly provide type arguments for the <code>Select</code> method since the compiler would be unable to infer the types from the usage alone.</p>

<p><strong>Note:</strong> This was a follow-up to <a href="http://togaroga.com/blog/2009/11/you-dont-always-need-a-lambda-expression/">You don’t always need a lambda expression</a>.  As you can see this new functionality gives us many more opportunities to forgo a lambda expression since we are no longer limited to <code>Action</code> delegates.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/11/smarter-type-inference-with-c-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>You don&#8217;t always need a lambda expression</title>
		<link>http://togaroga.com/blog/2009/11/you-dont-always-need-a-lambda-expression/</link>
		<comments>http://togaroga.com/blog/2009/11/you-dont-always-need-a-lambda-expression/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 16:42:53 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[best-practice]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[lambda-expressions]]></category>
		<category><![CDATA[type-inference]]></category>

		<guid isPermaLink="false">http://togaroga.com/blog/?p=204</guid>
		<description><![CDATA[C# 3 gave us the lambda expression and ever since we have been using them to create abstract representations of terse, anonymous functions.

While expressive and helpful, they are not always needed.  Consider this example:

using System;
using System.Collections.Generic;
class Example
{
    static void Main()
    {
        [...]]]></description>
			<content:encoded><![CDATA[<p>C# 3 gave us the <em>lambda expression</em> and ever since we have been using them to create abstract representations of terse, anonymous functions.</p>

<p>While expressive and helpful, they are not always needed.  Consider this example:</p>

<p><pre class="prettyprint">using System;
using System.Collections.Generic;<br />
class Example
{
    static void Main()
    {
        new List&#60;Int32&#62; { 1, 2, 3 }
            .ForEach(i => Console.WriteLine(i));
    }
}</pre></p>

<p>The preceding code can be refactored to this:</p>

<p><pre class="prettyprint"><code>using System;
using System.Collections.Generic;<br />
class Example
{
    static void Main()
    {
        new List&#60;Int32&#62; { 1, 2, 3 }
            .ForEach(Console.WriteLine);
    }
}</pre></p>

<p>What is different?  In the second example we are simply passing the name of the method group that we wish to invoke.  Since <a href="http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx"><code>List&lt;T&gt;.ForEach</code></a> accepts a single parameter of type <code>Action&lt;T&gt;</code> we can leverage the flexibility afforded us by the C# compiler to pass a method group name (in this case <code>Console.WriteLine</code>) to this method.  The compiler helpfully creates the new <code>Action&lt;Int32&gt;</code> delegate behind the scenes.</p>

<p>In this instance refactoring doesn't improve performance (in fact, the resulting IL is identical), but it does present a more readable expression.  So I challenge you to find opportunities to forgo lambda expressions.  If you find yourself writing lambda expressions that look similar to the one I have used in the example, stop and evaluate it carefully to see if you really need it.</p>

<p>You will find this mental exercise rewarding as it will not only improve the expressivity of your code, but it will also force you to think carefully about its functional nature.</p>

<p><strong>Caveat:</strong> Since C# 3 does not support the ability to infer generic type arguments from the return types of method groups, this really only works for examples like I have posted.  They work because the examples allow type inference to be accomplished based on the types of the method's arguments.</p>

<p>In other words, C# 3 will only let you do this for methods that accept delegates in the <a href="http://msdn.microsoft.com/en-us/library/system.action.aspx"><code>Action</code></a> family (i.e. <code>Action</code>, <code>Action&lt;T&gt;</code>, etc.) since these delegates do not return any values.  Revisions to the type-inference algorithm in the C# 4 compiler changes this and opens up a lot of possibilities.  Check back soon for another article that will cover this topic in depth.</p>

<p><strong>Edit:</strong>  Here is the follow-up article: <a href="http://togaroga.com/blog/2009/11/smarter-type-inference-with-c-4/">Smarter type inference with C# 4</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/11/you-dont-always-need-a-lambda-expression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>All types are not compared equally</title>
		<link>http://togaroga.com/blog/2009/10/all-types-are-not-compared-equally/</link>
		<comments>http://togaroga.com/blog/2009/10/all-types-are-not-compared-equally/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 05:43:29 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[equality]]></category>
		<category><![CDATA[reference-types]]></category>
		<category><![CDATA[type-system]]></category>
		<category><![CDATA[value-types]]></category>

		<guid isPermaLink="false">http://togaroga.com/blog/?p=209</guid>
		<description><![CDATA[Here is a bit of a quiz: What does this program print?

using System;
using System.Collections.Generic;
class Person
{
    public String Name { get; set; }
}
class Example
{
    static void Main()
    {
        var people = new List&#60;Person&#62; { 
      [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a bit of a quiz: What does this program print?</p>

<p><pre class="prettyprint">using System;
using System.Collections.Generic;<br />
class Person
{
    public String Name { get; set; }
}<br />
class Example
{
    static void Main()
    {
        var people = new List&#60;Person&#62; { 
            new Person { Name = "George Washington" } };<br />
        Console.WriteLine(
            people.Contains(
                new Person { Name = "George Washington" }));
    }
}</pre></p>

<p>If you said &#8220;True&#8221; then unfortunately you would be incorrect &#8211; this program prints &#8220;False&#8221;.  Before I explain why this program prints &#8220;False&#8221; I would like to make one slight change to this program to make it print &#8220;True&#8221;.</p>

<p><pre class="prettyprint">using System;
using System.Collections.Generic;<br />
struct Person
{
    public String Name { get; set; }
}<br />
class Example
{
    static void Main()
    {
        var people = new List&#60;Person&#62; { 
            new Person { Name = "George Washington" } };<br />
        Console.WriteLine(
            people.Contains(
                new Person { Name = "George Washington" }));
    }
}</pre></p>

<p>Did you spot it?</p>

<p>If you look carefully you will notice that I changed the <code>Person</code> type to be a <code>struct</code> instead of a <code>class</code>.  Why would this make a difference?  In order to understand let&#8217;s take a brief tour of how C# (and the CLR) handle equality.</p>

<p>Whenever you create a type without overriding the <code>Equals</code> method or implementing the <code>IEquatable&lt;T&gt;</code> interface you relinquish control over how two instances of your type will be compared and accept the CLR&#8217;s default comparison mechanisms.  If your type is a reference type (a <code>class</code>) you will get identity equality and if your type is a value type (a <code>struct</code>) you will get value equality.</p>

<p><strong>Identity equality</strong></p>

<p>Reference types are called reference types because the object itself is stored on the managed heap and you access that object via a <em>reference</em> to that object.</p>

<p>When you compare two instances of a reference type (like the <code>Person</code> type in my first example) the CLR will compare the references to the objects to see if the references point to the same object.  Two reference types will only be equal if their reference point to the exact same object on the managed heap.  If the references are different the objects are not equal then neither are the objects &#8211; even if their fields are identical.</p>

<p>Identity equality asks this question:</p>

<blockquote>
  <p>Do these two references point to the same object on the managed heap?</p>
</blockquote>

<p><strong>Value equality</strong></p>

<p>Value equality is a different process but is actually much simpler to understand.  Value equality takes all instance fields of a value type and compares them to the instance fields of a second instance in respective order.  I would imagine that value equality works much the way most developers expect <em>all</em> equality checks ought to.</p>

<p>Value equality asks this question:</p>

<blockquote>
  <p>For each field in these two instances, are all the values equal?</p>
</blockquote>

<p>So does this mean that in order to have value equality we must use value types?  Of course not!  I will soon publish a follow-up article explaining the proper way to do value equality with reference types and also why a boxed value type can never be used for reference equality.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/10/all-types-are-not-compared-equally/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Know your framework</title>
		<link>http://togaroga.com/blog/2009/10/know-your-framework/</link>
		<comments>http://togaroga.com/blog/2009/10/know-your-framework/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 13:02:49 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[best-practice]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.togaroga.com/blog/?p=159</guid>
		<description><![CDATA[What is wrong with the following program?

using System;
using System.Net;
using System.IO;
using System.Text;
class Example
{
    static void Main()
    {
        Console.WriteLine(
            getWebPage("http://example.com"));
    }
    static String getWebPage(String url)
   [...]]]></description>
			<content:encoded><![CDATA[<p>What is wrong with the following program?</p>

<p><pre class="prettyprint">using System;
using System.Net;
using System.IO;
using System.Text;<br />
class Example
{
    static void Main()
    {
        Console.WriteLine(
            getWebPage("http://example.com"));
    }<br />
    static String getWebPage(String url)
    {
        WebRequest request = WebRequest.Create(url);
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(stream);
        return streamReader.ReadToEnd();
    }
}</pre></p>

<p>At first glace there doesn&#8217;t appear to be anything wrong at all &#8211; the program compiles and runs.  This program does exactly what it sets out to do.</p>

<p>So what is the problem?  Perhaps this second example will help you see better what was wrong with the first one:</p>

<p><pre class="prettyprint">using System;
using System.Net;<br />
class Example
{
    static void Main()
    {
        Console.WriteLine(
            new WebClient().DownloadString("http://example.com"));
    }
}</pre></p>

<p>The problem is now quite apparent: the .NET framework has a method that allows you to retrieve a string response from a URL.  If the developer who wrote the first example had known this they would have saved a lot of time and effort by using the framework method that accomplishes the task instead of creating their own.</p>

<p>This is a simple example of an all too common problem:</p>

<blockquote>
  <p><strong>Many developers don&#8217;t know their frameworks.</strong></p>
</blockquote>

<p>Why is it important to know your framework?  You write less code and spend less time working on algorithms that have already been designed and tested by someone else.  Also the person who wrote the framework (let&#8217;s face it) is probably a lot smarter than you or me and was able to write a better implementation that we could have.</p>

<p>Finally, you must think about the readability of your code.  What is easier to understand, a custom method that the reader must read to continue understanding your program or a framework method that they are most likely already familiar with?  Consider the first example and the <code>getWebPage</code> method.  Another programmer reading the the <code>Main</code> method of this program would have to read the entire implementation of the <code>getWebPage</code> method to understand what it does.  This same programmer would most likely be familiar with the <code>WebClient.DownloadString</code> method from the .NET framework and would instantly understand what was going on and if they didn&#8217;t they would be able to consult the documentation of the framework.</p>

<p>So if you don&#8217;t already know your framework how do you go about learning it?  You need to be constantly pushing yourself to learn new things.  Does your IDE offer auto-complete information about the libraries you use?  Try turning that off occasionally to see how much you remember.  Other times leave it on and explore the APIs of your framework and see what methods are out there that you haven&#8217;t used before.</p>

<p>Before you begin designing a solution to a problem, search the internet for other folks who have solved the same problem.  These searches will either lead you to framework documentation or code examples that will help you solve problems using existing functionality.</p>

<p>In conclusion it is important to remember that you won&#8217;t always get this right and you will re-implement framework functionality by mistake.  But if you strive to find reusable components before writing your own you will make this mistake less often.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/10/know-your-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ASP.NET, JavaScript, and the mangled ID</title>
		<link>http://togaroga.com/blog/2009/10/asp-net-jquery-and-the-mangled-id/</link>
		<comments>http://togaroga.com/blog/2009/10/asp-net-jquery-and-the-mangled-id/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 03:41:56 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.togaroga.com/blog/?p=137</guid>
		<description><![CDATA[Many times I see folks struggling with a problem like this:


  I really want to get at an ASP.NET control with JavaScript but once the control has rendered, the ID of the control gets mangled to look something like ctl00_Content_foo_bar. How do I go about working with this control in JavaScript since the ID [...]]]></description>
			<content:encoded><![CDATA[<p>Many times I see folks struggling with a problem like this:</p>

<blockquote>
  <p>I really want to get at an ASP.NET control with JavaScript but once the control has rendered, the ID of the control gets mangled to look something like <code>ctl00_Content_foo_bar</code>. How do I go about working with this control in JavaScript since the ID is dynamically generated?</p>
</blockquote>

<p>There are many possible solutions to this problem:</p>

<ol>
<li>Hard-code this ID into your JavaScript code. </li>
<li>Generate your JavaScript code in your code-behind as a string so that you can embed the ID dynamically. </li>
<li>Add a CSS class to the control and use something like jQuery&#8217;s CSS selectors to find our control (other JavaScript frameworks have similar methods). </li>
<li>Find some way to pass the ID down to the JavaScript by squirreling it away in a hidden input or invisible element. </li>
</ol>

<p>While these solutions may work they are far from ideal. Here are the problems I see:</p>

<ol>
<li>The practice of hard-coding is brittle and any changes to your ASP.NET code could potentially break your JavaScript code. </li>
<li>This solution has potential but still is ugly since you now have to maintain your JavaScript as a string and since the code no longer lives in a separate file, browsers will no longer be able to cache your JavaScript locally. </li>
<li>Finding an element by a CSS class sacrifices performance to work (it is much slower than selecting by ID). </li>
<li>This final solution has promise as well but requires a lot of plumbing and extra markup to accomplish something that should be simple. </li>
</ol>

<p>Here is a better solution:</p>

<blockquote>
  <p><strong>Wrap your ASP.NET control&#8217;s markup in a plain HTML element and give that element an ID.</strong></p>
</blockquote>

<p>Here is an example:</p>

<p><pre class="prettyprint">&#60;div id="fooWrapper"&#62;
    &#60;asp:textbox id="foo" runat="server"/&#62;
&#60;/div&#62;</pre></p>

<p>Now that you have wrapped your control in an HTML element that is not set to be <code>runat="server"</code>, its ID will not be mangled when the page is rendered. This means you can retrieve the textbox by first finding its parent and then finding the next immediate child element of type <code>input</code>.</p>

<p>Here is how I would do it using jQuery:</p>

<p><pre class="prettyprint">textBox = $("#fooWrapper input:text");</pre></p>

<p>I truly believe this is the simplest and most straightforward solution to this problem and it will also provide better performance that most other options.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/10/asp-net-jquery-and-the-mangled-id/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Two casts are not better than one</title>
		<link>http://togaroga.com/blog/2009/09/two-casts-are-not-better-than-one/</link>
		<comments>http://togaroga.com/blog/2009/09/two-casts-are-not-better-than-one/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 01:57:06 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[casting]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://www.togaroga.com/blog/?p=53</guid>
		<description><![CDATA[C# has an interesting operator know as &#8220;is&#8220;.  The is operator is used for execution-time type checking.  It is a binary operator that returns a Boolean indicating whether or not the instance in question is in fact of the type specified as the second operand.

Here is an example:

using System;
class Example
{
    [...]]]></description>
			<content:encoded><![CDATA[<p>C# has an interesting operator know as &#8220;<a href="http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx"><code>is</code></a>&#8220;.  The <code>is</code> operator is used for execution-time type checking.  It is a binary operator that returns a <code>Boolean</code> indicating whether or not the instance in question is in fact of the type specified as the second operand.</p>

<p>Here is an example:</p>

<p><pre class="prettyprint">using System;<br />
class Example
{
    static void Main()
    {
        Console.WriteLine("hello, world" is String);  // True
    }
}</pre></p>

<p>Obviously this is a simple example but I am sure that the reader is capable of extrapolating more practical usages of <code>is</code>.  There is an inherent problem with <code>is</code> however that many developers are not aware of:</p>

<blockquote>
  <p><strong>Under the covers, the <code>is</code> operator uses a cast to make its determination.</strong></p>
</blockquote>

<p>Why is this a problem?  The reason it it a problem is because the next step most developers take is to cast the instance to the type.  This is viewed as a sort of &#8220;safe cast&#8221; since you know that the instance is of that type.  Here is an example of this practice:</p>

<p><pre class="prettyprint">using System;<br />
class Dog
{
    public void Speak() { Console.WriteLine("Bark!"); }
}<br />
class Example
{
    static void Main()
    {
        Object obj = new Dog();<br />
        if (obj is Dog)
            ((Dog)obj).Speak();  // Bark!
    }
}</pre></p>

<p>In this example there are actually two separate casts, the <code>is</code> and the explicit cast below it (inside the conditional statement).  You shouldn&#8217;t cast more then once if you don&#8217;t need to do so.  Also, the <code>is</code> check does not consider user-defined conversions (such as implicit and explicit cast operators) so <code>is</code> may return <code>false</code> for an instance that could have successfully been casted.</p>

<p>So what should we do instead?</p>

<p>Enter C#&#8217;s true safe casting operator: <a href="http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx"><code>as</code></a>.  The <code>as</code> operator allows you do do an explicit cast on a type while avoiding any <code>InvalidCastExceptions</code> that may occur by assigning <code>null</code> to the variable if the cast fails.</p>

<p>Here is an example of how to use <code>as</code>:</p>

<p><pre class="prettyprint">using System;<br />
class Dog
{
    public void Speak() { Console.WriteLine("Bark!"); }
}<br />
class Example
{
    static void Main()
    {
        Object obj = new Dog();<br />
        Dog dog = obj as Dog;
        if (dog != null)
            dog.Speak();
    }
}</pre></p>

<p>This example only contains one cast and also allows you to avoid any exceptions that may occur at execution time.</p>

<p>So, the important thing to remember is that if you feel like you need to use <code>is</code>, most likely you ought to use <code>as</code>.</p>

<p><strong>Note:</strong> Be careful that you are not using casting to solve a problem that would be better solved with polymorphism.  If you find that you are doing multiple checks for different types, casting, and then calling methods on those types, you should reevaluate your approach to see if a polymorphic solution would be better.  Casting is a powerful tool but it can be misapplied.</p>
]]></content:encoded>
			<wfw:commentRss>http://togaroga.com/blog/2009/09/two-casts-are-not-better-than-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
