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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With