Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast as generic interface returns null

Tags:

c#

generics

I have an interface:

public interface IReminder<T> where T : class, IIdentifiableEntity
{
    IEnumerable<T> GetRemindersToBeSent(IRepository<T> repository);

}

and class TimesheetReminder that implements this interface:

public class TimesheetReminder : IReminder<InvoiceSummary>
{

    public IEnumerable<InvoiceSummary> GetRemindersToBeSent(IRepository<InvoiceSummary> invoiceSummaryRepository)
    {
        var today = DateTime.Today;
        return invoiceSummaryRepository.List.Where(inv =>
            inv.InvoiceSummaryStatus.CKAStatusName == "Draft" &&
            inv.InsertDateUTC <= today.AddDays(-3)            &&
            inv.InsertDateUTC >= today.AddDays(-6)            &&
            inv.EndDate       <= today.AddDays(-3)
        );
    }

The InvoiceSummary implements IIdentifyableEntity, yet

public static class ReminderFactory<T> where T : class, IIdentifiableEntity
{
    public static IReminder<T> GetReminder(string applicationType)
    {
        IReminder<T> reminder;

        switch (applicationType)
        {
            case "Invoicing":
                reminder = (IReminder<T>)new TimesheetReminder();
                break;
            default:
                reminder = null;
                break;
        }

        return reminder;
    }
}

Invoicing case returns null.

If TimesheetReminder didn't implement IReminder of an IIdentifiableEntity I would understand it, but it does.

What am I doing wrong?

like image 570
Stuart Brant Avatar asked Dec 22 '25 23:12

Stuart Brant


2 Answers

What is T? TimeSheetReminder is IReminder<InvoiceSummary> so if T is not InvoiceSummary then the reference conversion is not possible:

class Foo: IIdentifiableEntity { ... }
var reminder = new TimesheetReminder() as IReminder<Foo>; //returns null
like image 184
InBetween Avatar answered Dec 24 '25 14:12

InBetween


Try following....

IReminder<InvoiceSummary> reminder = new TimesheetReminder() as IReminder<InvoiceSummary>; 
like image 44
Rudra Avatar answered Dec 24 '25 13:12

Rudra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!