title: C# generic collections
body: <p>I'm coming to C# from a Java background and keep bumping in to the same sort of problem with generics that would be trivial to solve in Java.</p>
  
  <p>Given the classes:</p>
  
  <pre><code>interface IUntypedField { }
  class Field&lt;TValue&gt; : IUntypedField { }
  
  interface IFieldMap
  {
      void Put&lt;TValue&gt;(Field&lt;TValue&gt; field, TValue value);
      TValue Get&lt;TValue&gt;(Field&lt;TValue&gt; field);
  }
  </code></pre>
  
  <p>I'd like to write something like:</p>
  
  <pre><code>class MapCopier
  {
      void Copy(IEnumerable&lt;IUntypedField&gt; fields, IFieldMap from, IFieldMap to)
      {
          foreach (var field in fields)
              Copy(field, from, to); // &lt;-- clearly doesn't compile as field is IUntypedField not Field 
      }
  
      void Copy&lt;TValue&gt;(Field&lt;TValue&gt; field, IFieldMap from, IFieldMap to)
      {
          to.Put(field, from.Get(field));
      }
  }
  </code></pre>
  
  <p>In Java this would simple to solve as the fields collection would be an <code>Iterable&lt;Field&lt;?&gt;&gt;</code> and you could call <code>Copy(Field, IFieldMap, IFieldMap)</code> directly.</p>
  
  <p>In C# I find myself doing switch/cast for all possible values of <code>TValue</code> (which smells horrifically, having to add a case for every type you add is clearly a bug waiting to happen, and only feasible if the set of types are finite):</p>
  
  <pre><code>foreach (var field in fields)
  {
      switch (field.Type) // added an enum to track the type of Field's parameterised type
      {
      case Type.Int:   Copy((Field&lt;int&gt;)field, from, to); break;
      case Type.Long:  Copy((Field&lt;long&gt;)field, from, to); break; 
      ...
      }
  }
  </code></pre>
  
  <p>The other option I sometimes do is to move the functionality in to the Field class, which again, stinks.  It's not the responsibility of the field.  At least this avoids the huge switch:</p>
  
  <pre><code>interface IUntypedField { void Copy(IFieldMap from, IFieldMap to); }
  class Field&lt;TValue&gt; : IUntypedField 
  { 
      void Copy(IFieldMap from, IFieldMap to)
      {
          to.Put(this, from.Get(this));
      }
  }
  
  ...
  
      foreach (var field in fields)
          field.Copy(from, to);
  </code></pre>
  
  <p>If you could write polymorphic extension methods (i.e. the Copy methods in IUntypedField and Field above) then you could at least keep the code in alongside the class whose responsibility it is.</p>
  
  <p>Am I missing some feature of C# that would make this possible.  Or is there some functional pattern that could be used?  Any ideas?</p>
  
  <p>(One last thing, I'm currently stuck on .Net 3.5, so can't make use of any covariance/contravariance, but would still be interested to know how they would help here, if at all).</p>