2

I have a IList .

 IList<MyClass> MyList
    {
        get;
        set;
    }

I copy a list of Myclass to this in page load

MyList=Listofmyclass;

I want add a new item to MyList

MyList.Add(NewItem);

but when i use this code i get error "Collection was of a fixed size."

How to add new item to IList?

Niloo
  • 1,205
  • 5
  • 29
  • 53
  • 6
    where is the definition of Listofmyclass? – ChrisBint Nov 19 '12 at 09:31
  • I definition in load before of MyList=Listofmyclass; – Niloo Nov 19 '12 at 09:36
  • But what **is** the `Listofmyclass`? Maybe you have `MyList is MyClass[]` and then you can't add. See the yellow box on the [MSDN Array doc](http://msdn.microsoft.com/en-us/library/system.array.aspx) where it states: _The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw `NotSupportedException`._ – Jeppe Stig Nielsen Nov 19 '12 at 10:04

3 Answers3

1

I assume that MyList is an MyClass[]. An array has a fixed size, you cannot add items to it. Instead i would assign a List<MyClass> instead which supports it if possible.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Probably is you have a fixed size implementation of Listofmyclass, in other words:

IsFixedSize == true

this prevent addition/removal of list elements.

IList implementations fall into three categories: read-only, fixed-size, and variable-size. A read-only IList cannot be modified. A fixed-size IList does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size IList allows the addition, removal, and modification of elements.

See here

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • Note: The above link is about the non-generic `IList` from .NET 1. The same is true for the `IList` of .NET 2 and so on, except that the generic interface does not have an `IsFixedSize` property. – Jeppe Stig Nielsen Nov 19 '12 at 09:51
0

You can only add items to an IList if the actual type of the collection supports adding. In your case it doesn't. If you are for example using an array, it doesn't support adding.

You can use the ToList method to turn your collection into a list, which supports adding:

MyList = Listofmyclass.ToList();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005