IList trouble. Fixed size?
Solution 1
The Split
method returns an array, and you can't resize an array.
You can create a List<string>
from the array using the ToList
extension method:
IList<string> stelle = stelleString.Split('-').ToList();
or the List<T>
constructor:
IList<string> stelle = new List<string>(stelleString.Split('-'));
Besides, you probably don't want to use the IList<T>
interface as the type of the variable, but just use the actual type of the object:
string[] stelle = stelleString.Split('-');
or:
List<string> stelle = stelleString.Split('-').ToList();
This will let you use exactly what the class can do, not limited to the IList<T>
interface, and no methods that are not supported.
Solution 2
string.Split
returns a string array. This would indeed have a fixed size.
You can convert it to a List<string>
by passing the result to the List<T>
constructor:
IList<string> stelle = new List<string>(stelleString.Split('-'));
Or, if available, you can use the LINQ ToList()
operator:
IList<string> stelle = stelleString.Split('-').ToList();
Solution 3
It has a fixed size cause string.Split returns a string[]. You need to pass the return value of split to a List<string> instance to support adding additional elements.
Solution 4
Call ToList()
to the result:
IList<string> stelle = stelleString.Split('-').ToList();
Related videos on Youtube
markzzz
Updated on November 09, 2020Comments
-
markzzz over 3 years
I have this code :
IList<string> stelle = stelleString.Split('-'); if (stelle.Contains("3")) stelle.Add("8"); if (stelle.Contains("4")) stelle.Add("6");
but seems that IList have a fixed size after a .Split() : System.NotSupportedException: Collection was of a fixed size.
How can I fix this problem?
-
BoltClock over 12 years
string.Split()
returns a string array. Arrays are of fixed size, hence the exception you're getting. -
mbeckish over 12 yearsThis is due to bad design decisions in .NET: stackoverflow.com/questions/5968708/why-array-implements-ilist/…
-
-
markzzz over 12 yearsThis could be a problem if the stelleString is "". I should put it on a try catch....
-
Guffa over 12 years@markzzz: If the string doesn't contain the delimiter, the
Split
method returns an array with a single item, containing the original string. If you want to handle that differently, atry...catch
won't help, you have to checkCount
of the list. -
Admin almost 12 yearsSounds like System.Array implements IList<T> syntactically but not semantically. Unfortunate.