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?
The underlying problem here is that
System.Arrayviolates the substitution principle by implementingIList<T>. ASystem.Arraytype has a fixed size which cannot be changed. The Add method onIList<T>is intended to add a new element to the underlying collection and grow it’s size by 1. This is not possible for aSystem.Arrayand hence it throws.What
System.Arrayreally wants to implement here is a read only styleIList<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>andCollection<T>. The list is too long to put here. The best way to see it all is to openIList<T>in reflector and look for derived types ofIList<T>.