Reputation: 321
I'm currently trying to add a collection of interfaces to another collection - the problem is, i only want the extended interface, and not the parent.
Let me elaborate:
interface IScanner
{
void scan();
}
interface IPhotocopier : IScanner
{
void Copy();
}
public class PrintingBusiness
{
List<IPhotocopier> Photocopiers { get; set; }
}
public class ScannerBusiness
{
List<IScanner> Scanners { get; set; }
}
public class Program
{
static void Main(string[] args)
{
PrintingBusiness printerBusiness = new PrintingBusiness();
printerBusiness.Photocopiers = new List<IPhotocopier>();
printerBusiness.Photocopiers.Add(new HPPrinter());
printerBusiness.Photocopiers.Add(new CanonPrinter())
ScannerBusiness scannerBusiness = new ScannerBusiness();
scannerBusiness.Scanners = new List<IScanner>();
scannerBusiness.Scanners.Add(printerBusiness.Photocopiers); // Here i want to retreive all the IScanners from my Photocopiers collection, but i get an ArgumentError: Cannot Convert from List<IPhotocopier> to List<IScanner>.
}
}
I want to access the collection of IScanner interfaces from my Photocopiers collection - i thought i could do it directly by simply adding the Photocopiers collection to my Scanners collection - but to i need to iterate over each Photocopier and cast to IScanner and then add them to my Scanners collection? :-)
Upvotes: 0
Views: 54
Reputation: 156978
You should use the AddRange
method, since that can iterate over the Photocopiers
list and add all those items to the Scanners
list:
scannerBusiness.Scanners.AddRange(printerBusiness.Photocopiers);
You won't need any conversion since the IPhotocopier
instances can implicitly be casted to IScanner
.
Also, don't forget to initialize your lists. They are null
now.
Upvotes: 3