BindingList Collection Is Read-Only

June 17th 2013 Binding .NET Framework

What's wrong with the following piece of code?

var array = new string[] { };
var bindingList = new BindingList<string>(array);

It might seem just fine to you, but if you try to run it, it will throw a NotSupportedException in the last line:

Collection is read-only.

How come?

If you read closely the documentation for the constructor used, it might become clear. When you pass an instance of IList<T> to the constructor, the BindingList<T> doesn't create its copy. It serves as a wrapper for it, supporting only the operations also supported by the underlying collection. Since an array implements IList<T> as a read-only collection, BindingList<T> throws the above mentioned exception when you try to modify it in any way. Interestingly enough, array doesn't implement non-generic IList as read-only:

var array = new string[] { };

Anyway, keep in mind that BindingList is only a wrapper for the collection you pass it, therefore any changes made to BindingList will automatically also be applied to the underlying collection. This might be okay if you're aware of it, otherwise make sure you pass a copy of your list to the BindingList to keep it unchanged:

var listToModify = new List<string>();
var listNotToModify = new List<string>();

// wrapper modifies inner list
var bindingListWrapper = new BindingList<string>(listToModify);
// doesn't change original list
var bindingListCopy = new BindingList<string>(listNotToModify.ToList());

As far as passing an array to BindingList constructor goes: I can't think of a case when this would be useful.

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Creative Commons License