SilentRage47
SilentRage47

Reputation: 952

IReadOnlyList<T> to BindingList

I'm trying to bind a IReadOnlyList of a Material class I made to a ComboBox but I can't find a way to make this works.

var bList = new BindingList<Material>(listToBind);

This gives me Argument type 'System.Collections.Generic.IReadOnlyList<Data.Material>' is not assignable to parameter type 'System.Collections.Generic.IList<Data.Material>'

Do I need to cast it to IList or is there any other way to accomplish this ?

Upvotes: 1

Views: 542

Answers (2)

Alex
Alex

Reputation: 39

In MSDN:

BindingList(IList)
Initializes a new instance of the BindingList class with the specified list.

So you need an object which implements IList; IReadOnlyList does not.

You could achive what you want with the following code:

var bList = new BindingList<Material>(listToBind.ToList());

Upvotes: 0

BindingList<T> does not have a constructor that takes any of the interfaces an IReadOnlyList extends.

BindingList<T> has two constructors (MSDN docs), one is empty, and the other takes an IList<T>. However, IReadOnlyList<T> extends IEnumerable<T>, which means it provides the function .ToList() that gives us a List<T> that we can use to populate our BindingList<T>.

The final code would then look like this:

var bList = new BindingList<Material>(listToBind.ToList());

Upvotes: 2

Related Questions