Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed Size to List

Tags:

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?

like image 264
user196546 Avatar asked Oct 26 '09 14:10

user196546


People also ask

Does a list have a fixed size?

Lists by default are allowed to grow/shrink in Java. However, that does not mean you cannot have a List of a fixed size. You'll need to do some work and create a custom implementation. You can extend an ArrayList with custom implementations of the clear, add and remove methods.

How do I declare a fixed size list in Python?

int* a = new int[10];

Do lists have a fixed size Python?

Although Python lists are not fixed-size and constrained like arrays in C++ or Java, they are still array type data structures where the items contained are stored in memory sequentially and accessed by an index number representing the memory block for a specific element. A list object can contain duplicate elements.


2 Answers

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

like image 91
JaredPar Avatar answered Oct 13 '22 20:10

JaredPar


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"; 
like image 34
Jake Pearson Avatar answered Oct 13 '22 19:10

Jake Pearson