Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'System.Collections.Generic.List< >' to 'System.Collections.Generic.IList< >'

Tags:

c#

linq

There are lots of possible duplicates for this post.But i tried most of thems, unfortunately my error still happens.

Error is : Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<Report.Business.ViewModels.InvoiceMaster>' to 'System.Collections.Generic.IList<ICSNew.Data.InvoiceHD>'. An explicit conversion exists (are you missing a cast?)

public IList<InvoiceHD> GetAllInvoiceMasterDetailsByInvoiceId(int InvoiceId)
{
    var dbMstDtl = ireportrepository.GetAllInvoiceMasterDetailsByInvoiceId(InvoiceId);

    var MstDtl = from mst in dbMstDtl 
                 select new Report.Business.ViewModels.InvoiceMaster 
                 {
                     ModifiedDate = mst.ModifiedDate,
                     SubTotal = Convert.ToDecimal(mst.SubTotal),
                     TotalDiscount = Convert.ToDecimal(mst.TotalDiscount),
                     VAT = Convert.ToDecimal(mst.VAT),
                     NBT = Convert.ToDecimal(mst.NBT),
                     AmtAfterDiscount = Convert.ToDecimal(mst.AmtAfterDiscount)
                 };

    return MstDtl.ToList();
}

In some post i saw this thing solved when they use return MstDtl.AsEnumerable().ToList();

But in my case it also not working(getting errors)

like image 649
TechGuy Avatar asked Dec 05 '22 05:12

TechGuy


1 Answers

Assuming InvoiceMaster derives from or implements InvoiceHD, and that you're using C# 4 and .NET 4 or higher, you can just use generic variance:

return MstDtl.ToList<InvoiceHD>();

This uses the fact that an IEnumerable<InvoiceMaster> is an IEnumerable<InvoiceHD> because IEnumerable<T> is covariant in T.

Another way to solve it would be to change the declaration of MstDtl to use explicit typing:

IEnumerable<InvoiceMaster> MstDtl = ...;

(I'd also suggest following regular C# naming, where local variables start with a lower-case letter, but that's a different matter.)

like image 196
Jon Skeet Avatar answered Dec 29 '22 00:12

Jon Skeet