9

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Vengrovskyi
  • 307
  • 1
  • 4
  • 9

1 Answers1

12

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?

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276