IList trouble. Fixed size?
Asked Answered
A

5

26

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?

Abuttal answered 8/11, 2011 at 14:48 Comment(2)
string.Split() returns a string array. Arrays are of fixed size, hence the exception you're getting.Sharpeyed
This is due to bad design decisions in .NET: https://mcmap.net/q/21283/-why-array-implements-ilist/…Turfman
W
27

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.

Whatley answered 8/11, 2011 at 14:50 Comment(2)
This could be a problem if the stelleString is "". I should put it on a try catch....Abuttal
@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, a try...catch won't help, you have to check Count of the list.Whatley
O
13

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();
Oriflamme answered 8/11, 2011 at 14:50 Comment(1)
Sounds like System.Array implements IList<T> syntactically but not semantically. Unfortunate.Casaba
P
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.

Pint answered 8/11, 2011 at 14:51 Comment(0)
J
2

Call ToList() to the result:

IList<string> stelle = stelleString.Split('-').ToList();
Jack answered 8/11, 2011 at 14:51 Comment(0)
S
0

String.split return an array. But you can redimensionate array. In VB it is

ReDim perserve myarray(newlength minus one)
Sylvia answered 8/11, 2011 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.