0

I am attempting to use generics so I can dynamically pass various different model lists to Excel sheets for export. I was hoping to use the class below to make my final list of models to export.

    public class ExcelExport<T>
    {
        public List<T> ExportList { get; set; }
        public string SheetName { get; set; }

    }

This is one of my many failed attempted usages: Cannot convert List(object) to List<ExcelExport>

//Export Declaration        
public async Task<byte[]> ExportToExcelAsync<T>(List<ExcelExport<T>> excelExports)
//Attempted calls
        var export = new List<object>();
        var list1 = getTypeList1Data();
        export.Add(new ExcelExport<TypeList1>() { ExportList = list1, SheetName = "Sheet1" });
        var list2 = getTypeList2Data();
        export.Add(new ExcelExport<TypeList2>() { ExportList = list2, SheetName = "Sheet2" });
        var result = await _excelFunctions.ExportToExcelAsync<object>(export);

Hoping some more versed in generics than myself might have a solution?

chrisg229
  • 909
  • 2
  • 7
  • 21
  • 1
    Your first problem is you are expecting generic `List` covariance, which would be invalid - see [this answer](https://stackoverflow.com/a/2033921/2557128). Instead, change `ExcelExport` to have `IEnumerable ExportList` property. Now `ExportList` is read-only and has covariance. – NetMage Apr 10 '23 at 20:38
  • Thanks NetMage, I did assume covariance! For now I will simply go with List which seems to do the trick. – chrisg229 Apr 10 '23 at 21:44

0 Answers0