Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - Why System.Array class implements IList but does not provide Add()

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why Array does not actually provide Add()?

Array has fixed size, so you cannot add new element(s).

The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance. https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx

Why did it have to implement IList in the first place?

Definition of IList: Represents a non-generic collection of objects that can be individually accessed by index.

https://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx

Array is accessed by index and IList accommodate this index, which is why Array implements IList.

For reference: Why array implements IList?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...