markzzz
markzzz

Reputation: 47945

What is incorrect in this List<List>?

This seems correct :

IList<IList<string>> MyList = new List<IList<string>>();
IList<string> List_Temp = new List<string>();
MyList .Add(List_Temp );

This seems incorrect :

IList<List<string>> MyList = new List<List<string>>();
IList<string> List_Temp = new List<string>();
MyList .Add(List_Temp );

why the second is incorrect?

Upvotes: 1

Views: 216

Answers (4)

horgh
horgh

Reputation: 18534

Compiler says that it cannot cast "System.Collections.Generic.IList<string>" to "System.Collections.Generic.List<string>";

List<T> is defined as follows:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

while IList<T> is

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

So, List<T> can be cast to IList<T>. Not vice versa.

Upvotes: 1

Gyan Chandra Srivastava
Gyan Chandra Srivastava

Reputation: 1380

object type should be same every time when you are adding into list your mylist list object type is list and you used to add iList in it

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

MyList contains elements of type List<string> but you are trying to add an element of type IList<string>.

Upvotes: 3

Dennis
Dennis

Reputation: 37770

Because you're trying to add some IList implementation istead of List class, which is requirement by definition - IList<List>. Look at this:

IList<List<string>> MyList = new List<List<string>>();
IList<string> List_Temp = new Collection<string>(); // ooops!
MyList .Add(List_Temp );

The second line of sample is correct, because Collection<T> implements IList<T>, but the third line is incorrect, because Collection<T> doesn't inherit List<T>.

Upvotes: 12

Related Questions