Question

Just getting my feet wet with extension methods and am currently developing some mapping logic to convert an application Invoice to a Quickbooks Invoice. Thought it might be a good idea to have .Convert() extension method.

public static QBInvoice Convert(this InvoiceHeader importedInvoice)

The conversion is just field mapping of one class to another. But then I read somewhere that an extension method is to extend the original class, not convert it to another. Hence why I am asking. I know technically I can do it, but is it best practice compliant or taboo?

No correct solution

OTHER TIPS

Personally I like to use explicit casts so:

public class InvoiceHeader
{
   public static explicit operator QBInvoice(InvoiceHeader invoice)
   {
      return new QBInvoice {}; // do your mapping
   }
}

Then you can just cast it:

var qbInvoice = (QBInvoice) invoiceHeader;

we use it to map classes all the time... probably not the best solution but at least you hide boring unnecessary code somewhere far away and make the code that matters (your business logic) nice and readable.

I must strongly disagree with Blogbeard's comment above: mapping between classes has nothing to do with the class itself (SRP) so putting that code outside either of the two classes is way cleaner solution.

A great well-accepted conversion method for classes, defined as an extension method is ToArray(). AsEnumerable, ToList, and ToDictionary are other well-accepted "conversion" extension methods.

"To" or "As" seem to be acceptable naming conventions for extension methods which convert to another type, just as "On" is part of a standard naming convention for events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top