Fixed Size to List
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 Li开发者_Python百科st<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.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";
@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.
精彩评论