Why array implements IList?
Asked Answered
R

8

163

See the definition of System.Array class

public abstract class Array : IList, ...

Theoretically, I should be able to write this bit and be happy

int[] list = new int[] {};
IList iList = (IList)list;

I also should be able to call any method from the iList

 ilist.Add(1); //exception here

My question is not why I get an exception, but rather why Array implements IList?

Recognition answered 11/5, 2011 at 18:15 Comment(8)
Good question. I never liked the idea of fat interfaces (that’s the technical term for this kind of design).Doorstop
The real (better) question would be why it supports IList<T>. IList is legacy.Boykin
How do you think it breaks substitution? I think it doesn't. See Brians answer.Boykin
@Henk, see: blogs.msdn.com/b/bclteam/archive/2004/11/19/267089.aspxPolysyndeton
Does anybody actually care about LSP? It seems quite academic to me.Haunting
@Gabe, then you need to work with larger codebases. Implementing a behavior (inheriting from an interface) and then simply ignoring the things you don't like/can't support leads to smelly, obfuscated, casting and finally: buggy code.Mannino
@Marius: You have to put the complexity somewhere. Let's say you have a method that can sort a member of its class. With a single IList<> interface, you can check IsReadOnly to see if you can sort. If you have separate IRWList<> and IReadList<> interfaces, what type do you make the member of your class? You can't use IRWList<> because then it couldn't hold read-only objects, so you have to make it a IReadList<> and then cast to IRWList to do your sorting. See -- smelly, obfuscated casting.Haunting
@Haunting its the collection which implies mutability not its contained entities. You can make your class member of a type that implements both IRWList<> and IReadList<>, use if as IRWList<> internally in your class and expose it as IReadList. Yes, you have to put complexity somewhere, but I just don't see how that applies to disregarding LSP as a very good design principle (did not know about the IsReadOnly property though which makes IList more complex from a consumers standpoint)Mannino
H
108

Because an array allows fast access by index, and IList/IList<T> are the only collection interfaces that support this. So perhaps your real question is "Why is there no interface for constant collections with indexers?" And to that I have no answer.

There are no readonly interfaces for collections either. And I'm missing those even more than a constant sized with indexers interface.

IMO there should be several more (generic) collection interfaces depending on the features of a collection. And the names should have been different too, List for something with an indexer is really stupid IMO.

  • Just Enumeration IEnumerable<T>
  • Readonly but no indexer (.Count, .Contains,...)
  • Resizable but no indexer, i.e. set like (Add, Remove,...) current ICollection<T>
  • Readonly with indexer (indexer, indexof,...)
  • Constant size with indexer (indexer with a setter)
  • Variable size with indexer (Insert,...) current IList<T>

I think the current collection interfaces are bad design. But since they have properties telling you which methods are valid (and this is part of the contract of these methods), it doesn't break the substitution principle.

Hiles answered 11/5, 2011 at 18:22 Comment(9)
thanks for the answer. But I rather leave the question as is. The reason is simple. Interface is a public contract. If one implements it, one must fully implement all the members, otherwise it breaks LSP and generally smells bad, is it not?Recognition
@olek But there is no good alternative to IList<T> atm since this is the only collection interface with an indexer. And all the code that needs an indexer thus uses IList<T>, in particular many linq methods do(Skip,ElementAt,Reverse,...)Hiles
It does break LSP. If it didn't list.Add(item) should add item to the list regardless of the concrete type. Except for exceptionel cases. In the array implementation in throws an exception in a non-exceptionel case, which in it self is bad practiceNamnama
@RuneFS it doesn't break LSP, you're just using it wrong. You should be checking IsFixedSize or IsReadOnly before attempting to mutate the object.Vardar
@Vardar I'm sorry but you got LSP wrong then. An array does not implement add and thus can't be substituted for something that does when that ability is required.Namnama
I concede that it technically does not violate LSP only because the documentation states you should check the IsFixedSize and IsReadOnly properties, it definitely violates the Tell, Don't Ask principle and Principle of least surprise. Why implement an interface when you're just going to throw exceptions for 4 out of the 9 methods?Census
Some time has passed since the original question. But now with .Net 4.5, there are additional interfaces IReadOnlyList and IReadOnlyCollection.Insecure
Very simply this was done to avoid breaking changes which people would have complained about a lot more vocally than this.Briquette
it does not breaks LSP if you check IsReadonly or IsFixedSize but it violate Open/Close. check LSP here #4429225Doc
T
46

The remarks section of the documentation for IList says:

IList is a descendant of the ICollection interface and is the base interface of all non-generic lists. IList implementations fall into three categories: read-only, fixed-size, and variable-size. A read-only IList cannot be modified. A fixed-size IList does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size IList allows the addition, removal, and modification of elements.

Obviously, arrays fall into the fixed-size category, so by the definition of the interface it makes sense.

Topotype answered 11/5, 2011 at 18:23 Comment(7)
I guess they would have ended up with a lot of interfaces. IListFixedSize, IListReadOnly...Saffian
that'a actually a good answer from the documentation's point of view. But to me it rather looks like a hack. Interfaces must be thin and simple in order for a class to implement all the members.Recognition
@oleksii: I agree. Interfaces and runtime exceptions are not the most elegant combination. In defense of Array it does implement the Add method explicitly, which reduces the risk of calling it by accident.Topotype
Until we create an implementation of IList that disallows both modification and addition/removal. Then the documentations is no longer correct. :PGrane
@Saffian - In .Net 4.5, there are additional interfaces IReadOnlyList and IReadOnlyCollection.Need
@Need But afaik, unfortunately not the opposite to exclude collections that can't be written to.Sadi
@BrianRasmussen unless you were trying to expose an interface to not force a concrete implementation.Sadi
B
19

Because not all ILists are mutable (see IList.IsFixedSize and IList.IsReadOnly), and arrays certainly behave like fixed-size lists.

If your question is really "why does it implement a non-generic interface", then the answer is that these were around before generics came along.

Blowup answered 11/5, 2011 at 18:24 Comment(2)
@oleksii: No, it doesn't break LSP, because the interface IList itself tells you that it may not be mutable. If it was in fact guaranteed to be mutable and the array told you otherwise, then it would break the rule.Blowup
Actually, Array does break LSP in case of generic IList<T> and doesn't break it in case of non-generic IList: enterprisecraftsmanship.com/2014/11/22/…Kalindi
K
7

It's a legacy that we have from the times when it wasn't clear how to deal with read only collections and whether or not Array is read only. There are IsFixedSize and IsReadOnly flags in the IList interface. IsReadOnly flag means that collection can't be changed at all and IsFixedSize means that collection does allow modification, but not adding or removal of items.

At the time of .Net 4.5 it was clear that some "intermediate" interfaces are required to work with read only collections, so IReadOnlyCollection<T> and IReadOnlyList<T> were introduced.

Here is a great blog post describing the details: Read only collections in .NET

Kalindi answered 22/11, 2014 at 14:40 Comment(1)
An array is not read only you can simply set values at indexes. An array just has a fixed size but there isn't an IFixedSizeList .Faxan
H
0

Definition of IList interface is "Represents a non-generic collection of objects that can be individually accessed by index.". Array completely satisfies this definition, so must implement the interface. Exception when calling Add() method is "System.NotSupportedException: Collection was of a fixed size" and occurred because array can not increase its capacity dynamically. Its capacity is defined during creation of array object.

Holding answered 11/5, 2011 at 18:30 Comment(0)
C
0

Having an array implement IList (and transitively, ICollection) simplified the Linq2Objects engine, since casting the IEnumerable to IList/ICollection would also work for arrays.

For example, a Count() ends up calling the Array.Length under-the-hood, since it's casted to ICollection and the array's implementation returns Length.

Without this, the Linq2Objects engine would not have special treatment for arrays and perform horribly, or they'd need to double the code adding special-case treatment for arrays (like they do for IList). They must've opted to make array implement IList instead.

That's my take on "Why".

Collinear answered 14/2, 2020 at 10:59 Comment(0)
D
0

Also implementation details LINQ Last checks for IList , if it did not implement list they would need either 2 checks slowing down all Last calls or have Last on an Array taking O(N)

Dimorph answered 8/4, 2020 at 3:41 Comment(0)
F
0

An Array is just one of many possible implementations of IList.

As code should be loosely coupled, depend on abstractions and what not... The concrete implementation of IList that uses consecutive memory (an array) to store it's values is called Array. We do not "add" IList to the Array class that's just the wrong order of reasoning; Array implements IList as an array.

The exception is exactly what the interface defines. It is not a surprise if you know the whole interface not just a single method. The interface also give you the opportunity to check the IsFixedSize property and see if it is safe to call the Add method.

Faxan answered 8/12, 2022 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.