Contravariance in inheritance

Is there a way to make the return type contravariant in inherited types? See sample code below. I need this for Entity Framework.

public class InvoiceDetail
{
    public virtual ICollection<Invoice> Invoices { get; set; }
}

public class SalesInvoiceDetail : InvoiceDetail
{
    //This is not allowed by the compiler, but what we are trying to achieve is that the return type 
    //should be ICollection<SalesInvoice> instead of ICollection<Invoice>
    public override ICollection<SalesInvoice> Invoices { get; set; }
}

      

+3


source to share


1 answer


You can apply generics with appropriate constraints



public abstract class InvoiceDetailBase<T> where T : Invoice
{
    public virtual ICollection<T> Invoices { get; set; }
}

public class InvoiceDetail : InvoiceDetailBase<Invoice>
{
}

public class SalesInvoiceDetail : InvoiceDetailBase<SalesInvoice>
{
}

      

+5


source







All Articles