user317891
user317891

Reputation: 23

Converting from an interface to an object that implements the interface?

I have an interface which is implemented by several different objects. What I am trying to do is write a method in c# that will accept the interface object as a parameter and convert this parameter to an object that it implements so i don't have to write the same function for several different types. Such as:

Class UnappliedCashDetails implements interface ITransactionDetail.

Constructor for ISSBatch:

public ISSBatch(List<ITransactionDetail> details)

public static ISSBatch GetNextReceiptBatch() { List<UnappliedCashDetail> details = new List<UnappliedCashDetail>();

    /`*`some code here to populate my list`*`/            

    return = new ISSBatch(details);

}

C# does not like this. Am i trying to use the interface wrong or just not casting correctly?

Thanks!

Upvotes: 0

Views: 590

Answers (1)

Anthony Pegram
Anthony Pegram

Reputation: 126814

You're passing a List<UnappliedCashDetail> to a constructor that accepts List<ITransactionDetail>. UnappliedCashDetail may very well implement ITransactionDetail, but this type of variance is not supported by C#. Consider that inside the constructor (or any other method) you could attempt to add an instance of SomeOtherTransactionDetail to your details list, except that the details list should really only accept UnappliedCashDetail, as per its declaration.

To make your code work, you need to change your declaration

List<ITransactionDetail> details = new List<ITransactionDetail>();      
/* some code here to populate my list */                  
return new ISSBatch(details);

Or you could simply change your constructor to accept IEnumerable<ITransactionDetail>, in which case your original List<UnappliedCashDetail> declaration would work. Variance is supported for IEnumerable<T> (note: C# 4), since it is just a sequence and cannot be added to, deleted from, etc., so there's no possibility of trying to add an AppliedCashDetail instance to a sequence of UnappliedCashDetail objects.

Upvotes: 2

Related Questions