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?
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.
int* a = new int[10];
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.
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>.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With