Vengrovskyi
Vengrovskyi

Reputation: 307

IList<T> array and Collection is read-only ERROR

During fixing bug in one project find interesting issue

IList<int> a =new List<int>();
var b = new int[2];
b[0] = 1;
b[1] = 2;
a = b;
a.Clear();

This code is throws exception on a.Clear(); I know how to fix it but I didn't clearly get all steps which leads to this NotSupported exception. And why compiler didn't throws compile time error?

Upvotes: 9

Views: 2564

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109597

Yes, this is a somewhat annoying feature of standard C# arrays: They implement IList<>, as defined by the C# language.

Because of this, you can assign a standard C# array to an IList<> type, and the compiler will not complain (because according to the language, an array IS-A IList<>).

Alas, this means that you can then try to do something to change the array such as IList<>.Clear() or IList<>.Add() and you will get a runtime error.

For some discussion about why the language is defined like this, see the following thread:

Why array implements IList?

Upvotes: 12

Related Questions