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?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 2
    `string.Split()` returns a string array. Arrays are of fixed size, hence the exception you're getting. – BoltClock Nov 08 '11 at 14:50
  • This is due to bad design decisions in .NET: http://stackoverflow.com/questions/5968708/why-array-implements-ilist/5968798#5968798 – mbeckish Nov 08 '11 at 14:58

5 Answers5

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This could be a problem if the stelleString is "". I should put it on a try catch.... – markzzz Nov 08 '11 at 14:53
  • 1
    @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. – Guffa Nov 08 '11 at 15:12
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();
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 2
    Sounds like System.Array implements IList syntactically but not semantically. Unfortunate. –  Aug 08 '12 at 20:28
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.

Jehof
  • 34,674
  • 10
  • 123
  • 155
2

Call ToList() to the result:

IList<string> stelle = stelleString.Split('-').ToList();
Yogu
  • 9,165
  • 5
  • 37
  • 58
0

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

ReDim perserve myarray(newlength minus one)
Iesvs
  • 125
  • 2