How to apply Generics methods

I use FileHelper.dll to convert list to csv and it works fine.

As a result, I have 9 lists and corresponding 9 methods for processing file conversions, and it will grow in the future

Here I showed only 3 methods.

 //-----Transaction.csv public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<RetailTransaction> retailTxnList) { engine = new FileHelperEngine(typeof(RetailTransaction)) { HeaderText = HeaderLine }; engine.WriteFile(filePath, retailTxnList); return DateTime.Now; } //-----ConcessionSale.csv public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<ConcessionSale> concessionSaleList) { engine = new FileHelperEngine(typeof(ConcessionSale)) { HeaderText = HeaderLine }; engine.WriteFile(filePath, concessionSaleList); return DateTime.Now; } //-----MerchandiseSale.csv public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<MerchandiseSale> merchandiseSaleList) { engine = new FileHelperEngine(typeof(MerchandiseSale)) { HeaderText = HeaderLine }; engine.WriteFile(filePath, merchandiseSaleList); return DateTime.Now; } 

While Googling, I read some concepts in Generics , however I cannot get an idea. My concern, you can use Generics . Like one general method instead of many methods as described above.

Please shed light on this issue. Is it possible to reduce the number of methods?

Thanks in advance.

+1
source share
2 answers
 public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> data) { engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine }; engine.WriteFile(filePath, data); return DateTime.Now; } 

For more information on generics, see this article on MSDN.

+3
source

This is a situation where you can use generics. You should use a type variable, usually T, so you usually see it. This variable will replace the type of your list. As a result, you will need to pass the list type when calling the method

 public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> SaleList) { engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine }; engine.WriteFile(filePath, SaleList); return DateTime.Now; } 

and then you can simply call it like this:

 ExportResultsToCsv(filePath,Header,salesList) 
+2
source

Source: https://habr.com/ru/post/1500076/


All Articles