    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: C# Generics - Beyond Containers of T</title>
        <link>https://members.accu.org/index.php/journals/1376</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #74 - Aug 2006 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c200/">74</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c200-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c200+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;C# Generics - Beyond Containers of T</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 August 2006 11:56:00 +01:00 or Tue, 01 August 2006 11:56:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Steve Love takes a look at generics in C# v2.0, how to use them to simplify code and even remove dependencies.</p>
<p><strong>Body:</strong>&nbsp;<p>One of the bigger differences between the latest version of C# and its predecessors is the addition of Generics. This facility is in fact provided and supported by the runtime (actually the Common Language Infrastructure, or CLI, specification), and exposed in the language of C# from version 2.0. Programmers already familiar with C++ templates or Java generics will immediately spot that they share a common base motivation with C# - the provision of type-safe generic containers of <i>things</i>. Syntactically they are similar, too, but it would have been grotesque for C# to choose an entirely different syntax just to be unique. Where these languages really diverge is in the implementation details. A discussion of these differences is beyond the scope of this article; this isn't a comparison between languages, rather an exploration of what C# generics offer. If you think that means you can do:
  </p><pre class="programlisting">
public class Stack&lt; T &gt;
{
}
    </pre><p>
    and
  </p><pre class="programlisting">
private T Swap&lt; T &gt; ( T left, T right )
{
}
    </pre><p>
    well, you're right, but that's not the whole story. This article is for people who already <i>know</i> you can do those things and are starting to wonder if they can do anything else.
  </p><h2>
    Groundwork
  </h2><p>
    At its most basic level, using generics is about writing less code. At a slightly higher level, it's about saying what you mean <i>in code</i>. Without generics, the contents of a list have to be manually cast from <tt class="code">object</tt> to obtain the real thing. With a generic list container, you write <i>less code </i>because the casts are no longer required. A list container parameterised on the type of its contents also <i>says what it is</i> right on the tin. Speak less, say more.
  </p><p>
    The next thing generics give you is support from your compiler. If you try to get an integer out of a container of strings, the compiler tells you you're dumb. Defects like this, if left until the program runs, are much harder to find and fix. Generics provide stronger <i>type-safety</i>. Wise programmers depend on their compilers being smarter than they are, however smug the error messages are.
  </p><p>
    Note that all the above is about <i>using</i> generic types, delegates, methods, etc.. If you're writing generic code, you need to invest a bit in allowing the programmers <i>using</i> your code to write less code, say what they mean and expect the compiler to spot their misuses. Given that often the &quot;other programmers&quot; will be you later on, it's worth every penny.
  </p><h2>
    The example (nope - it's not a stack)
  </h2><p>
    Double Dispatch [<a href="#Wiki">Wiki</a>] is a common pattern used to figure out the concrete type of an object when all you have is an interface. The Visitor Pattern is often used for this, but the intent of Double-Dispatch is different. A common example is for <tt class="code">Shape</tt> objects, and a basic implementation is in Listing 1. For the purposes of the example, the <tt class="code">ShapeHandler</tt> class has a <tt class="code">Receive</tt> method to stand-in for client code. The important point is that the code needs to access the concrete <tt class="code">Shape</tt> instances when it has only a <tt class="code">Shape</tt> interface available.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
interface Shape
{
  void Accept&lt; HandlerType &gt;( HandlerType handler );
}
class Circle : Shape
{
  void Shape.Accept&lt; HandlerType &gt;(
     HandlerType handler )
    {
      ( ( Handler&lt; Circle &gt; )handler ).Handle(
         this );
    }
}
class Square : Shape
{
  void Shape.Accept&lt; HandlerType &gt;(
     HandlerType handler )
    {
      ( ( Handler&lt; Square &gt; )handler ).Handle(
         this );
    }
}
interface Handler
{
    void Receive( Shape s );
    void Handle( Circle c );
    void Handle( Square s );
}
class ShapeHandler : Handler
{
    public void Receive( Shape shape )
    {
        shape.Accept( this );
    }
    public void Handle( Circle c )
    {
        Console.WriteLine( &quot;Circle&quot; );
    }
    public void Handle( Square s )
    {
        Console.WriteLine( &quot;Square&quot; );
    }
}
</pre></td></tr><tr><td class="title">Listing 1</td></tr></table>
    <p>
    What's worth paying attention to in this example is what would be required if a new member of the <tt class="code">Shape</tt> hierarchy gets added: the <tt class="code">Handler</tt> interface grows a new method, and the <tt class="code">ShapeHandler</tt> implementation grows a new method in sympathy. This isn't too onerous, really, but it's a nasty dependency. All of the classes shown must be in the same assembly, because to do otherwise would introduce a circular reference, which is not allowed. In practice this means that the <tt class="code">Handler</tt> interface is redundant. We could just as easily use the concrete <tt class="code">ShapeHandler</tt> object in the <tt class="code">Accept</tt> methods.
  </p><p>
    We can use C# generics to remove some of the code duplication in this example, and more importantly, we can break the dependency between the <tt class="code">Handler</tt> interface, and the concrete implementations of the <tt class="code">Shape</tt> interface.
  </p><p>
    There are two areas in the example for Listing 1 where code is duplicated. Firstly, each of the concrete implementations of the <tt class="code">Shape</tt> interface require an <tt class="code">Accept</tt> method which contains identical code. Further implementations of <tt class="code">Shape</tt> require <i>exactly the same code</i>. The second duplication is also a source of the dependency already mentioned: each of the implementations of <tt class="code">Shape</tt> is mentioned in both the <tt class="code">Handler</tt> interface and its implementation.
  </p><p>
    The ideal situation we'd like to achieve is to have the <tt class="code">Shape</tt> and <tt class="code">Handler</tt> interfaces living in their own assemblies (or perhaps a single common interfaces assembly), with concrete <tt class="code">Shape</tt>s in one separate assembly, and the concrete <tt class="code">ShapeHandler</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>in another. We also want to divorce the <tt class="code">Accept</tt> method from the <tt class="code">Shape</tt> interface: it is not a <tt class="code">Shape</tt>'s responsibility to do double dispatch, it has other things to think about. We can in fact go one step further, and remove the duplication in the <tt class="code">Square</tt> and <tt class="code">Circle</tt> classes by moving the <tt class="code">Accept</tt> method to a base class.
  </p><h2>
    The Handler
  </h2><p>
    The first pass at breaking this up is to remove the dependency between the <tt class="code">Handler</tt> interface and the concrete <tt class="code">Shape</tt> classes. This is where C#'s generics can help.
  </p><p>
    Generic code is representable regardless of the types it operates on (although we'll talk about type constraints later). &quot;Representable&quot; usually means some combination of:
  </p>
		<ul><li>
    An algorithm works irrespective of the types on which it operates - e.g. Swap or sort.
  </li><li>
    The storage of objects is the same whatever their type - e.g. Containers of &quot;T&quot;.
  </li></ul><p>
    Our requirements don't really fit either of these: the whole point of using double-dispatch is to vary the behaviour on the concrete type of the object we have in hand, and we're not really storing objects. What we can say is that the <i>interface</i> for the <tt class="code">Handler</tt> is the same for each type of <tt class="code">Shape</tt> object we consider. By using a generic <i>interface</i>, our <tt class="code">Handler</tt> interface and <tt class="code">ShapeHandler</tt> implementation become as shown in Listing 2.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
interface Handler&lt; HandledType &gt;
{
  void Receive( Shape s );
  void Handle( HandledType c );
}
class ShapeHandler : Handler&lt; Circle &gt;,
   Handler&lt; Square &gt;
{
  public void Receive( Shape s )
  {
    s.Accept( this );
  }
public void Handle( Circle c )
    {
        Console.WriteLine( &quot;Circle handled&quot; );
    }
    public void Handle( Square s )
    {
        Console.WriteLine( &quot;Square handled&quot; );
    }
}
</pre></td></tr><tr><td class="title">Listing 2</td></tr></table>
<p>
    This code demonstrates a simple use of generics, where the <tt class="code">Handler</tt> has a generic parameter indicating the handled type. This handled type is then used by the <tt class="code">Handle</tt> method declaration. When the interface is implemented, a <tt class="code">Handle</tt> method for each of the generic <i>arguments</i> (in this case <tt class="code">Circle</tt> and <tt class="code">Square</tt>) must be implemented. <tt class="code">Handler</tt> is a straightforward generative interface. In particular, it allows <tt class="code">ShapeHandler</tt> to explicitly declare what types of <tt class="code">Shape</tt> it is a handler for - it is like a label on a tin.
  </p><p>
    Note that the <tt class="code">Handler</tt> interface no longer has the dependencies upon <tt class="code">Circle</tt> and <tt class="code">Square</tt>. This means we can safely put the <tt class="code">Handler</tt> interface into a separate assembly, and have broken that part of the dependency circle. It presents other challenges, though.
  </p><p>
    Recall from Listing 1 that the <tt class="code">Shape</tt> interface looked like this:
  </p><pre class="programlisting">
interface Shape
{
  void Accept( Handler handler );
}
    </pre><p>
    Now that the <tt class="code">Handler</tt> interface has a generic parameter, this is no longer valid. The problem is, what would we put as the argument to it?
  </p><pre class="programlisting">
interface Shape
{
  void Accept( Handler&lt; ? &gt; handler );
}
    </pre><p>
    We could use the <tt class="code">ShapeHandler</tt> class directly, but that would again make the <tt class="code">Handler</tt> interface redundant, and would re-introduce the circular dependency between <tt class="code">Shape</tt> and <tt class="code">ShapeHandler</tt>. We could try the same trick as with <tt class="code">Handler</tt> and make <tt class="code">Shape</tt> a generic, but that would cause a different kind of difficulty. If <tt class="code">Shape</tt> were generic, we would have to name its type parameter at every use, precluding uses like
  </p><pre class="programlisting">
List&lt; Shape&lt; ? &gt; &gt; shapes;
    </pre><p>
    The answer is to use a generic method. Instead of making the whole of the <tt class="code">Shape</tt> interface generic, we make only its <tt class="code">Accept</tt> method generic. A first attempt might look like this:
  </p><pre class="programlisting">
void Accept&lt; ShapeType &gt;(
  Handler&lt; ShapeType &gt; handler )
    </pre><p>
    This would be valid, parameterising <tt class="code">Handler</tt> on the generic parameter of <tt class="code">Accept</tt>, but we have now moved the problem of what to put as a generic argument back to <tt class="code">ShapeHandler</tt>, in its <tt class="code">Receive</tt> method:
  </p><pre class="programlisting">
public void Receive( Shape s )
{
  s.Accept( this );
}
    </pre><p>
    This does not compile because the call to <tt class="code">Shape.Accept</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>is ambiguous: &quot;<tt class="code">this</tt>&quot; could be interpreted as either a <tt class="code">Handler&lt; Circle &gt;</tt> or a <tt class="code">Handler&lt; Square &gt;</tt> in this context, and we cannot explicitly specify which to use, because at this point, we know only that we have a <tt class="code">Shape</tt>&lt;sup class=&quot;footnoteref&quot;&gt;. </sup>The best we can manage is to make the entire type of the handler a generic parameter.
  </p><pre class="programlisting">
void Accept&lt; HandlerType &gt;(
  HandlerType handler );
    </pre><p>
    We then need some way to tell the compiler the actual contents of the handler in the <tt class="code">Accept</tt> method, and generics can't help here: a runtime cast is required. Listing 3 shows the new <tt class="code">Shape</tt> hierarchy with this in place. <tt class="code">ShapeHandler</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>and its interface remain as in Listing 2.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
interface Shape
{
  void Accept( Handler handler );
}
class Circle : Shape
{
  public void Accept( Handler handler )
  {
    handler.Handle( this );
  }
}
class Square : Shape
{
  public void Accept( Handler handler )
  {
    handler.Handle( this );
  }
}
</pre></td></tr><tr><td class="title">Listing 3</td></tr></table>
  <p>
    Note that it's not possible to cast an <i>unconstrained</i> generic parameter to just anything. A cast to <tt class="code">object</tt> is always valid, and a cast to an interface type (which is used here) is also OK. Constraining the parameter can make further casts valid.
  </p><p>
    This code works because generics in C# are a <i>runtime</i> artifact. The <tt class="code">Accept</tt> method in <tt class="code">Shape</tt> is implicitly virtual, because it's declared in an interface type. Derived classes (<tt class="code">Circle</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>and <tt class="code">Square</tt>) inherit this method, and if code calls <tt class="code">Accept</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>using the <tt class="code">Shape</tt> reference, the over-ridden method in the concrete (runtime) type will get called. If you're already familiar with C++ templates, this is probably the biggest difference between them and C# Generics. In C++, templates are a purely <i>compile-time</i> construction, and it's not possible to have a virtual function template.
  </p><h2>
    Mission accomplished
  </h2><p>
    We have reached the point where the circular dependency between concrete <tt class="code">Shapes</tt> and the <tt class="code">Handler</tt> interface is gone. We can create a new project structure reflecting r&ocirc;les and responsibilities, with each different assembly having a specific r&ocirc;le:
  </p><p class="indented"> <b>HandlerInterface</b></p><p class="indented">
    -	interface Handler&lt; HandledType &gt;
  </p><p class="indented"> <b>ShapeInterface</b><i>depends upon HandlerInterface</i></p><p class="indented">
    -	interface Shape
  </p><p class="indented"> <b>Shapes</b><i>depends upon ShapeInterface and HandlerInterface</i></p><p class="indented">
    -	class Circle
  </p><p class="indented">
    -	class Square
  </p><p class="indented"> <b>Application</b><i> depends upon Shapes, ShapeInterface and HandlerInterface</i></p><p class="indented">
    -	class ShapeHandler
  </p><p>
    There are no circular references, and apart from the main application, all dependencies are on interface-only assemblies. If nothing else, this makes testing easier. There remain some opportunities for overtime, however: we can still improve on what we have. It's time to make good on the promise that we can reduce the amount of duplicated code, and in the process make the whole a bit more tidy and self-describing.
  </p><h2>
    The interfaces of shapes
  </h2><p>
    It has already been noted that the <tt class="code">Shape</tt> interface has too many responsibilities. Not only is it a shape, with all that implies, it is a shape that can take part in the double-dispatch mechanism we are describing here. That really isn't part of a <tt class="code">Shape</tt> interface.
  </p><p>
    This indicates the need for a new interface, which we'll call <tt class="code">Dispatchable</tt>. This interface exposes the double-dispatch mechanism in the same way as the old <tt class="code">Shape</tt> interface did - a generic <tt class="code">Accept</tt> method.
  </p><p>
    We can still do better. The implementations of the <tt class="code">Accept</tt> method in the concrete <tt class="code">Circle</tt> and <tt class="code">Square</tt> classes are identical. Each class now implements <tt class="code">Dispatchable</tt> as well as <tt class="code">Shape</tt>, but the <tt class="code">Accept</tt> method remains as it was in Listing 3. We have already identified that one of the uses of generic code is when an algorithm can operate regardless of the types using it: this is exactly that example.
  </p><p>
    We can therefore make a base class common to all concrete shapes which implements the <tt class="code">Accept</tt> method. Listing 4 shows a first try at what we want to achieve. Taking a leaf from a pattern normally associated with C++ - the Curiously Recurring Template Pattern [<a href="#Coplien95">Coplien95</a>] - each derived class parameterises its base class with itself.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
public class Dispatchable&lt; Dispatched &gt;
   : Dispatchable
{
  void Dispatchable.Accept&lt; HandlerType &gt;(
     HandlerType handler )
  {
    ( ( Handler&lt; Dispatched &gt; )handler ).Handle(
       this );
  }
}
public class Circle : Dispatchable&lt; Circle &gt;, Shape
{
}
</pre></td></tr><tr><td class="title">Listing 4</td></tr></table>
  <p>
    The observant among you will notice that we now have two types with the same name - <tt class="code">Dispatchable</tt>. C# allows types to be &quot;overloaded&quot; based on the number of generic parameters, and thus <tt class="code">Dispatchable</tt> and <tt class="code">Dispatchable&lt; Dispatched &gt;</tt> are distinct types.
  </p><p>
    Unfortunately this doesn't compile because the call to <tt class="code">Handle</tt> is passing <tt class="code">this</tt> -which is an instance of <tt class="code">Dispatchable&lt; Dispatched &gt;</tt>. Recall the <tt class="code">Handler</tt>&lt;sup class=&quot;footnoteref&quot;&gt; </sup>interface: it is a generic interface, where the <tt class="code">Handle</tt> method declaration uses the generic parameter. <tt class="code">ShapeHandler</tt> itself implements the <tt class="code">Handle</tt> method with the actual concrete type of the shape being used, and so expects either a <tt class="code">Circle</tt> or a <tt class="code">Square</tt>. The <tt class="code">Dispatched</tt> parameter is a generic handle for exactly that - depending on which concrete class implementation is in play - so we might try this:
  </p><pre class="programlisting">
( ( Handler&lt; Dispatched &gt; handler )
   .Handle( ( Dispatched )this );
    </pre><p>
    Alas this doesn't compile either. The difficulty is that the compiler doesn't know the type of <tt class="code">Dispatched</tt> because it is resolved <i>at runtime</i>. The types to which we can cast &quot;<tt class="code">this</tt>&quot; are strictly controlled: we can cast to <tt class="code">object</tt>, to any direct or indirect base class or interface of <tt class="code">this</tt>, or to the same type as <tt class="code">this</tt> - which is usually redundant, but permitted. It cannot be cast to a type that is, as far as the compiler is concerned, an unrelated type.
  </p><h2>
    Constraints
  </h2><p>
    A short diversion into a comparison between C++ templates and C# generics might be illustrative of what is going on. In C++, a template parameter represents <i>any</i> type, and being a compile-time construct, the compiler knows when some facility is used that the supplied argument to the template parameter doesn't support. In C# generic parameters are not resolved to types until <i>runtime,</i> so during compilation, the parameter still represents any type, but only as an <tt class="code">object</tt>, the ultimate base class of all types. Therefore only those operations supported by <tt class="code">object</tt> are permitted by the compiler, without extra information.
  </p><p>
    The extra information is provided either by explicitly casting<i> </i>the reference<i> </i>(as we've already seen), or by using <i>constraints</i> on the types allowed as arguments to that parameter. Listing 5 shows this in a simple way. Note there are several different types of constraint; a fairly detailed discussion can be found at [<a href="#MSDN">MSDN</a>].
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
struct Person
{
  public string Name
  {
    get { return name; }
  }
  private string name;
}
class PersonComparer
{
  public static bool Compare&lt; Sorted &gt;(
     Sorted left, Sorted right )
    where Sorted : Person
    {
      return string.Compare( left.Name,
                              right.Name ) &lt; 0;
    }
}
</pre></td></tr><tr><td class="title">Listing 5</td></tr></table>
  <p>
    The <tt class="code">where</tt> clause on the <tt class="code">PersonComparer</tt>. <tt class="code">Compare</tt> method tells the compiler that the parameters are <tt class="code">Person</tt> objects (or are derived from <tt class="code">Person</tt>), and thus have a <tt class="code">Name</tt> property. Without the constraint, this code won't compile because <tt class="code">object</tt> has no <tt class="code">Name</tt> property. In addition, if <tt class="code">PersonComparer</tt>. <tt class="code">Compare</tt> is called with arguments which are <i>not</i><tt class="code">Person</tt> objects, the compiler also issues an error - the constraint applies to the client code as well.
  </p><p>
    So finally we should be able to finish the generic <tt class="code">Dispatchable</tt> base class. From Listing 4, remember we need to be able to cast <tt class="code">this</tt> to a type suitable for the argument to <tt class="code">Handler&lt; Dispatched &gt;.Handle</tt> which accepts a reference to either <tt class="code">Circle</tt> or <tt class="code">Square</tt>. Depending on context, the <tt class="code">Dispatchable</tt> class is either a <tt class="code">Dispatchable&lt; Circle &gt;</tt> or <tt class="code">Dispatchable&lt; Square &gt;</tt>, with the concrete type substituted for the generic parameter <tt class="code">Dispatched</tt>.
  </p><p>
    In order to cast <tt class="code">this</tt> to <tt class="code">Dispatched</tt>, <tt class="code">Dispatched</tt> must be constrained to ensure it's actually <i>the same type as</i><tt class="code">this</tt>, so the class declaration becomes:
  </p><pre class="programlisting">
public class Dispatchable&lt; Dispatched &gt; : Dispatchable
   where Dispatched : Dispatchable&lt; Dispatched &gt;
    </pre><p>
    and the cast is now legal, allowing:
  </p><pre class="programlisting">
void Dispatchable.Accept&lt; HandlerType &gt;(
   HandlerType handler )
{
  ( ( Handler&lt; Dispatched &gt; )handler ).Handle(
     ( Dispatched )this );
}
    </pre><p>
    With this in place, we can now add the <tt class="code">Dispatchable</tt> interface, and perhaps the <tt class="code">Dispatchable&lt; Dispatched &gt;</tt> base class, since it depends only on the <tt class="code">Handler&lt; Dispatched &gt;</tt> interface, to the <tt class="code">Handler</tt> assembly, and the <tt class="code">Shape</tt> interface is completely independent of the double-dispatch mechanism.
  </p><p>
    The effort now required to add a new object to the <tt class="code">Shape</tt> family is to add the class, and inherit from <tt class="code">Dispatchable</tt>, add a new derivation to <tt class="code">ShapeHandler</tt>, and add the overloaded <tt class="code">Accept</tt> method. No copy-and-paste, and many mistakes in usage will be caught by the compiler. Another benefit of using this generic double-dispatch framework is that <tt class="code">ShapeHandler</tt> need not be the only handler: there could be multiple implementations of the <tt class="code">Handler</tt> interface, each handling a different set of <tt class="code">Shape</tt> objects, with no duplication in the interface or implementations.
  </p><p>
    Using a <tt class="code">Constraint</tt> for the <tt class="code">Dispatched</tt> parameter in the <tt class="code">Dispatchable&lt; Dispatched &gt;</tt> class gave the compiler extra information about <tt class="code">Dispatched</tt> which allowed us to use it as a cast target. The question now arises - could we apply a constraint to <tt class="code">HandlerType</tt> in the <tt class="code">Accept</tt> method and so remove the runtime cast?
  </p><p>
    Unfortunately, the answer is &quot;no&quot;.
  </p><p>
    An interface class specifies a contract which must be adhered to by implementing classes. A constraint on a generic parameter forms part of the interface, and therefore the contract, so implementing classes must match it exactly. The <tt class="code">HandlerType</tt> parameter would need a constraint in the <tt class="code">Dispatchable</tt> interface:
  </p><pre class="programlisting">
interface Dispatchable
{
  void Accept&lt; HandlerType &gt;(
  HandlerType handler ) where HandlerType :
  Handler&lt; ? &gt;;
}
    </pre><p>
    and we have no way of specifying what to use as the argument to <tt class="code">Handler</tt> at that point.
  </p><h2>
    In conclusion
  </h2><p>
    There is more to life - and generic code - than containers and simple functions. Generics in C# improve the type-safety of code, which in turn gives us, as programmers, much greater confidence that our code, once compiled, is correct.
  </p><p>
    The double-dispatch example shows how generics allow a generative interface to remove hard-wired dependencies, how classes can make use of a common generic base class to reduce code duplication, and demonstrated the run-time nature of C# generics, using virtual generic methods. In addition, it shows the trade-off of using type constraints on generic parameters, where restricting the types permitted by user code allows the generic code more freedom in its implementation.
  </p><p>
    There is much more to generics in C# than can be covered here, including using constraints to improve code efficiency, specifying <i>naked type constraints</i>, to<i> </i>match whole families of types (mimicking Java wild-cards), and creating arbitrary objects at runtime.
  </p><p>
    Generics in C# are not perfect - nothing is! - and there are limitations which can seem to be entirely gratuitous, but they provide a very powerful and expressive framework for improving code by allowing it to speak less, and say more.</p><h2>
    Acknowledgements
  </h2><p>
    The idea for using C# generics to implement double-dispatch is the result of inspiration from two sources:
  </p><p>
    Anthony Williams' article &quot;Message Handling Without Dependencies&quot; [<a href="#Williams06">Williams06</a>] discusses managing the dependency problem of double-dispatch in C++ using templates. This got me wondering whether anything like it was possible in C# using generics.
  </p><p>
    Jon Jagger has an Occasional Software Blog [<a href="#Jagger">Jagger</a>], where he uses the Visitor Pattern to demonstrate some properties of generics in C#. This showed me that double-dispatch probably <i>was</i> possible using C# generics.
  </p><p>
    Thanks to Phil Bass, Nigel Dickens, Pete Goodliffe, Alan Griffiths and Jon Jagger for their helpful comments and insights.
  </p><h2>
    References
  </h2><p class="reference">
    [<a name="Wiki"></a>Wiki] <a href="http://en.wikipedia.org/wiki/Double_dispatch">http://en.wikipedia.org/wiki/Double_dispatch</a>
  </p><p class="reference">
    [<a name="Coplien95"></a>Coplien95] James O Coplien, &quot;Curiously Recurring Template Pattern&quot;, C++ Report February 1995
  </p><p class="reference">
    [<a name="MSDN"></a>MSDN] MSDN, &quot;Constraints on Type Parameters (C# Programming Guide), <a href="http://msdn2.microsoft.com/en-us/library/d5x73970.aspx">http://msdn2.microsoft.com/en-us/library/d5x73970.aspx</a>
  </p><p class="reference">
    [<a name="Williams06"></a>Williams06] Anthony Williams, &quot;Message Handling Without Dependencies&quot;, Dr Dobb's Journal May 2006, issue 384, available on-line at <a href="http://www.ddj.com/dept/cpp/184429055">http://www.ddj.com/dept/cpp/184429055</a>
  </p><p class="reference">
    [<a name="Jagger"></a>Jagger] Jon Jagger, &quot;Less Code More Software (C# 2.0 - Visitor return type)&quot;, <a href="http://jonjagger.blogspot.com">http://jonjagger.blogspot.com</a>
  </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
