25

For declaration perspective the following is allowed

    IList<string> list= new string[3];
    list.Add("Apple");
    list.Add("Manago");
    list.Add("Grapes");

1) It compiles fine,But runtime i am getting "Collection was of fixed size" error. Ofcourse ,collection is dynamically grown by size,why did such declaration is accepted by complier ?

2) What are the different lists that i can assign to IList ? Example

IList<string> fruits=new List<string>();

Here I am assigning List to IList ,What are the various collection classes can i assign to IList?

3 Answers 3

43

The underlying problem here is that System.Array violates the substitution principle by implementing IList<T>. A System.Array type has a fixed size which cannot be changed. The Add method on IList<T> is intended to add a new element to the underlying collection and grow it's size by 1. This is not possible for a System.Array and hence it throws.

What System.Array really wants to implement here is a read only style IList<T>. Unfortunately no such type exists in the framework and hence it implements the next best thing: IList<T>.

As to the question about what types are assignable to IList<T>, there are actually quite a few including: ReadOnlyCollection<T> and Collection<T>. The list is too long to put here. The best way to see it all is to open IList<T> in reflector and look for derived types of IList<T>.

1
  • Dictionary<TKey, TValue> implements ICollection<T>, not IList<T>
    – thecoop
    Oct 26, 2009 at 15:04
6

When you call list.Add, you are trying to insert an item to the end of you array. Arrays are a fixed size collection so you can't do an Add. Instead you will have to assign the entries via the indexer:

list[0] = "a";
list[1] = "b";
list[2] = "c";
2

@Jake: Actually a string[] IS castable to an IList... but you can't ADD to it.

If you want to pre-populate the list, then you could use something like:

IList<string> list= new string[3] { "Apple", "Mango", "Grapes" };

but then what's the point of making it an IList? You still couldn't add to it. If it really is a fixed-sized list, then make it a string[]. Otherwise, make it a List(), as Jake suggests.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.