Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I press f12 on the ArrayList keyword to go to metadata generated from vs2008, I found that the generated class declaration as follows

public class ArrayList : IList, ICollection, IEnumerable, ICloneable 

I know that the IList already inherits from ICollection and IEnumerable, so why does ArrayList redundantly inherit from these interfaces?

like image 426
Ahmed Avatar asked Jun 21 '09 07:06

Ahmed


People also ask

Why collections are used in C#?

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.

What are collection classes?

Collections class is one of the utility classes in Java Collections Framework. The java. util package contains the Collections class. Collections class is basically used with the static methods that operate on the collections or return the collection.

What is collection in C programming?

A collection is a class, so you must declare an instance of the class before you can add elements to that collection. If your collection contains elements of only one data type, you can use one of the classes in the System. Collections. Generic namespace.

Are there collections in C?

There are two types of collections available in C#: non-generic collections and generic collections. The System. Collections namespace contains the non-generic collection types and System.


2 Answers

OK, I've done some research. If you create the following hierarchy:

  public interface One     {         void DoIt();     }      public interface Two : One     {         void DoItMore();     }      public class Magic : Two     {          public void DoItMore()         {             throw new NotImplementedException();         }          public void DoIt()         {             throw new NotImplementedException();         }     } 

And compile it, then reference the DLL in a different solution, type Magic and Press F12, you will get the following:

 public class Magic : Two, One     {         public Magic();          public void DoIt();         public void DoItMore();     } 

You will see that the interface hierarchy is flattened, or the compiler is adding the interfaces in? If you use reflector you get the same results too.

Update: If you open the DLL in ILDASM, you will see it saying:

implements ...Two

implements ...One.

like image 74
RichardOD Avatar answered Sep 19 '22 05:09

RichardOD


The extra interfaces are shown because they are implied by IList. If you implement IList, you must also implement ICollection and IEnumerable.

like image 43
Zr40 Avatar answered Sep 22 '22 05:09

Zr40