Ji Yalin
Ji Yalin

Reputation: 1250

Why ArrayList implement IList, ICollection, IEnumerable?

ArrayList declares that it implements the IList, ICollection, and IEnumeralbe interfaces.

Why not only implement IList, because IList is also derived from ICollection, and ICollection is derived from IEnumerable.

What's the purpose of this kind of declaration? There are many cases like this in .NET BCL.

Upvotes: 15

Views: 3565

Answers (4)

Kenan E. K.
Kenan E. K.

Reputation: 14111

There is no effective difference. I believe the extra declarations are there for clarity.

When checked in Reflector, classes which in code implement IList have the same interface declaration list as classes which in code declare implementing all of Ilist, ICollection and IEnumerable.

Upvotes: 13

Henk Holterman
Henk Holterman

Reputation: 273274

With the following code:

interface I1 { }
interface I2 : I1 { }

class Foo: I2 { }

If you look at Foo through reflection you will find

class Foo: I2, I1 { }

Which is also valid to compile and gives the same result.
So the difference is moot, and in documenting Foo you might as well write it with both interfaces.

Also see the SO question: Why collections classes in C# (like ArrayList) inherit from multiple interfaces if one of these interfaces inherits from the remaining?

Upvotes: 7

Fredrik Mörk
Fredrik Mörk

Reputation: 158319

I am not so sure that ArrayList has separate implementations of the interfaces. Consider the following code:

public interface IBase
{
    int SomeInt { get; set; }
}

public interface ISub : IBase
{
    int SomeOther { get; set; }
}

public class MyClass : ISub
{
    public int SomeOther { get; set; }
    public int SomeInt { get; set; }
}

The MyClass type implements only the ISub interface directly. However, if you compile the code into an assembly, and then add that assembly as reference in another project, open the Object Browser and examine the base types for MyClass, it will feature something like this:

Base Types
 |- ISub
 |    |- IBase
 |- IBase
 |- Object

Upvotes: 1

Partha
Partha

Reputation: 2192

  1. IEnumerable - To support the foreach statement
  2. ICollection - To support add single or multiple item in arraylist

Upvotes: -1

Related Questions