Search code examples
c#collectionsilist

IList trouble. Fixed size?


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?


Solution

  • 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.