C # why the System.Array class implements IList but does not provide Add ()

This code:

int[] myArr = { 1, 2 };
myArr.Add(3);

throws on build:

error CS1061: "System.Array" does not contain a definition for "Add", and the extension method "Add", which takes the first argument of type "System.Array", was not found (do you miss the using directive or the assembly?)

The IList interface has an Add () method, but why doesn't the array implement it?

UPDATE: I see from the answers that he implements this explicitly, OK, I get this, thanks, I should better ask myself:

Why does the array really not provide Add (), OR, is it better why it should implement IList in the first place? Instead of implementing IList, it could be another interface (for example, IArray), which can ONLY be useful for members of the IList-eg array. IsFixedSize, IsReadOnly, IndexOf () ... just a thought

+4
source share
7 answers

Yes, it seems that it was the best design if System.Arrayimplemented IReadOnlyListor a similar interface. However, it IReadOnlyList<T>appeared in .Net 4.5 , and System.Arrayremains from the initial .NET 1.0 . Microsoft, IMHO, did everything possible and hid it Addthrough an explicit implementation of the interface

http://referencesource.microsoft.com/#mscorlib/system/array.cs,156e066ecc4ccedf

  ...
int IList.Add(Object value)
{
    throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
} 
  ...

,

int[] myArr = { 1, 2 };

myArr.Add(3);

Add ( NotSupportedException throw)

((IList) myArr).Add(3);

if (!myArr.IsFixedSize) {
  // we have very strange array, let try adding a value to it
  ((IList) myArr).Add(3);
}
+3

, NotSupportedException (. MSDN), .

, , , , , , IList. . # .

+3

, , , :

public class MyList<T> : IList<T>
{
    // ... shortened for simplicity
    void ICollection<T>.Add(T item) {  } // explicit implementation
}

, MyList<T>:

MyList<int> list = new MyList<int>();
list.Add(5); // would NOT compile
((IList<int>)list).Add(5); // can be compiled

, int[], :

int[] array = new int[0];
((IList<int>)array).Add(5);

, NotSupportedException, , , (new int[0]).

+3

msdn:

IList.Add()

NotSupportedException.

Array Class - .

Array . , IList. , , .

+1

IList :

  • Readonly

, Array IList. , Add() Array, , :

public class A : IList {
    public void IList.Add(object o){
         ...
    }
}

, IList, Add ( , ).

, , .

: https://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx

+1

System.Array IList, Add()

, ( ).

IList?

, , , .

IList. IList IsFixedSize,

, , IList .

A fixed-size collection does not allow you to add or remove items after creating the collection, but allows you to modify existing items.

Thus, the array implementation returns IsFixedSize = trueand drops NotSupportedExceptionin methods Add, Insert, Removeand RemoveAt.

+1
source

All Articles