This code:
int[] myArr = { 1, 2 };
myArr.Add(3);
throws the following error on Build:
error CS1061: 'System.Array' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
IList
interface has the Add()
method, but why the Array does not implement it?
UPDATE: I see from the answers that it DOES implement it explicitly, OK, I get it, thank you, I should better stick to the question:
Why Array
does not actually provide Add()
, OR, better, why did it have to implement IList
in the first place? Instead of implementing IList
, it could be another interface (e.g. IArray
) which could have ONLY the useful for Array members of IList
-e.g. IsFixedSize
, IsReadOnly
, IndexOf()
... just a thought.
Yes, it seems that it should have been a better design if System.Array
had implemented IReadOnlyList
or alike interface. However, IReadOnlyList<T>
appeared in .Net 4.5 while System.Array
stays from the initial .Net 1.0. Microsoft, IMHO, did their best and hid Add
via explicit interface implementation
http://referencesource.microsoft.com/#mscorlib/system/array.cs,156e066ecc4ccedf
...
int IList.Add(Object value)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
}
...
So you can't do
int[] myArr = { 1, 2 };
myArr.Add(3);
but you can insist on using Add
(and get NotSupportedException
thrown) via
((IList) myArr).Add(3);
Or even
if (!myArr.IsFixedSize) {
// we have very strange array, let's try adding a value to it
((IList) myArr).Add(3);
}