Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass List of class to List of Interface?

I have a function like this:

DoSomething(List<IMyInterface>) 

IMyInterface is an interface and MyClass is a class implementing this interface Class MyClass:IMyInterface

I call DoSomething(List<MyClass>) and it looks it doesn't work. How could I pass the list of a class to a list of the interface of the class as function's parameter? Thanks!

like image 803
spspli Avatar asked Oct 03 '11 02:10

spspli


People also ask

What are the implementation classes of list interface in Java?

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5. Let us elaborate on creating objects or instances in a List class.

What are the methods of the list interface?

Methods of the List Interface 1 add (int index, element) 2 addAll (int index, Collection collection) 3 size () 4 clear () 5 remove (int index) 6 remove (element) 7 get (int index) 8 set (int index, element) 9 indexOf (element) 10 lastIndexOf (element) More items...

Can a List<MyClass> contain an instance of a class?

Now your List<MyClass> contains an instance of a class that is not a MyClass. This would violate type safety. (As other answers noted, you can avoid this problem by passing only the IEnumerable<> interface of List, which provides read-only access and so is safe).

How do you pass a reference to a List<MyClass> as list<IMyInterface>?

Suppose you pass someone a reference to a List<MyClass> as a List<IMyInterface>, then they do: void Foo (List<IMyInterface> list) { IMyInterface x = new MyOtherClassWhichAlsoImplementsIMyInterface (); list.Add (x); }


1 Answers

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<>.

like image 55
Anthony Pegram Avatar answered Oct 30 '22 02:10

Anthony Pegram