Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 685
Vengrovskyi Avatar asked Nov 06 '13 10:11

Vengrovskyi


1 Answers

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?

like image 54
Matthew Watson Avatar answered Sep 22 '22 02:09

Matthew Watson