IList trouble. Fixed size?

34,326

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();
Share:
34,326

Related videos on Youtube

markzzz
Author by

markzzz

Updated on November 09, 2020

Comments

  • markzzz
    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?

  • markzzz
    markzzz over 12 years
    This could be a problem if the stelleString is "". I should put it on a try catch....
  • Guffa
    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, a try...catch won't help, you have to check Count of the list.
  • Admin
    Admin almost 12 years
    Sounds like System.Array implements IList<T> syntactically but not semantically. Unfortunate.