title: C# generics based object to object mapper question
body: <p>I have the need for an object to object mapper in my application.  I've tried out a few, but haven't been able to find anything that fits my needs, so I'm writing my own.  Currently I have an interface like below:</p>
  
  <pre><code>public interface IMapper&lt;T, R&gt; {
      T Map(R obj);
  }
  </code></pre>
  
  <p>I then implement an AccountMapper that maps a Customer to an Account as:</p>
  
  <pre><code>public class AccountMapper : IMapper&lt;Account, Customer&gt; {
      Account Map(Customer obj) {
          // mapping code
      }
  }
  </code></pre>
  
  <p>This works fine so far, however I have several source entities that map to the same destination entity.  For instance I have a Payment and an Invoice that both map to BillHistory.  For the above to support this, I need to make two separate mappers (ie. BillHistoryPaymentMapper and BillHistoryInvoiceMapper), which is fine.  However, I'd love to be able to implement it slightly differently like below.  Only problem is I don't know if it's possible and if so, I don't know the correct syntax.</p>
  
  <pre><code>public interface IMapper&lt;T&gt; {
      T Map&lt;R&gt;(R obj);
  }
  
  public class BillHistoryMapper : IMapper&lt;Account&gt; {
      public BillHistory Map&lt;Invoice&gt;(Invoice obj) {
          // mapping code
      }
      public BillHistory Map&lt;Payment&gt;(Payment obj) {
          // mapping code
      }
  }
  </code></pre>
  
  <p>While the first implementation works fine, the second would be slightly more elegant.  Is this possible and if so what would the correct syntax look like?</p>
  
  <p>edit-------</p>
  
  <p>I hate when people do this, but of course I forgot to mention one little detail.  We have an abstract class between the mapper and the interface to implement some common logic across all of the mappers.  So my mapper signature is actually:</p>
  
  <pre><code>public class BillHistoryMapper : Mapper&lt;BillHistory, Invoice&gt; {
  }
  </code></pre>
  
  <p>where Mapper contains:</p>
  
  <pre><code>public abstract class Mapper&lt;T, R&gt; : IMapper&lt;T, R&gt; {
      public IList&lt;T&gt; Map(IList&lt;R&gt; objList) {
          return objList.ToList&lt;R&gt;().ConvertAll&lt;T&gt;(new Converter&lt;T, R&gt;(Map));
      }
  }
  </code></pre>