Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it appropriate to use extension methods to map one class to another

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?

like image 865
crichavin Avatar asked Jan 11 '23 02:01

crichavin


1 Answers

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;
like image 68
shenku Avatar answered Jan 29 '23 15:01

shenku