How to pass List of class to List of Interface?

If your code is simply iterating over the sequence inside the method (not adding, removing, or accessing by index), change your method to one of the following

DoSomething(IEnumerable<IMyInterface> sequence)
DoSomething<T>(IEnumerable<T> sequence) where T : IMyInterface

The IEnumerable<> interface is covariant (as of .NET 4) (first option). Or you could use the latter signature if using C# 3.

Otherwise, if you need indexed operations, convert the list prior to passing it. In the invocation, you might have

// invocation using existing method signature 
DoSomething(yourList.Cast<IMyInterface>().ToList());

// or updating method signature to make it generic
DoSomething<T>(IList<T> list) where T : IMyInterface

What the latter signature would allow you to do is to also support adds or removes to the list (visible at the callsite), and it would also let you use the list without first copying it.

Even still, if all you do is iterate over the list in a loop, I would favor a method acceping IEnumerable<>.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)