Simsons
Simsons

Reputation: 12735

Why is the Error Can not convert from ICollection<T> to List<T>

    List<Question> withTags = 
Question.GetRecentQuestionsWithTags(StackExchangeSite.StackOverflow, "c#");

The above code have a compile error;

Cannot implicitly convert type 'System.Collections.Generic.ICollection' to 'System.Collections.Generic.List'.

Though it works with .ToList() but why the error in first place?

List<t> implements from ICollection<T> and so does ICollection<Question>

Upvotes: 0

Views: 700

Answers (4)

Juri Robl
Juri Robl

Reputation: 5736

Because a ICollection is not a necessarily a List but could be any other collection as well, like a Dictionary.

Upvotes: 2

nvoigt
nvoigt

Reputation: 77285

Just because every List is an ICollection, it does not mean every ICollection is a List.

Just because every Doctor is a human being, that does not mean that every human being is a doctor.

Basic logic.

Upvotes: 2

Paweł Bejger
Paweł Bejger

Reputation: 6366

It is because ICollection cannot be implicitly casted to List. It would though go the other way round.

Upvotes: 1

Marko Juvančič
Marko Juvančič

Reputation: 5890

Add ToList()

List<Question> withTags = 
Question.GetRecentQuestionsWithTags(StackExchangeSite.StackOverflow, "c#").ToList();

You can always convert a list to a collection (List class is an ancesotor), but it doesn't go the other way around.

Upvotes: 0

Related Questions