Search code examples
arrays.netinterfaceicollection

Why don't array types have Add() method although they implement IList<T>?


Array types such as int[] implement many interfaces, and IList is one of them. IList requires to implement the Add(T) method (because IList inherits from ICollection).

I am writing a "CircularArray" class which contains an array in itself, but doesn't have any index out of range exceptions because of being circular. The class's definition is this:

public class CircularArray<T> : ICloneable, IList<T>, IStructuralComparable, IStructuralEquatable

It should implement all interfaces Arrays do, so i have to implement The Add method. But... Arrays don't have this method, although they implement the "ICollection" interface.

How is it all done for arrays so that they can implement the ICollection interface and not have Add method? I want to do the same for my CircularArray class.


Solution

  • The explanation is in Daniel's answer in the other topic. To do what you want to achieve is to use explicit interface implementation.

        interface ILeft
        {
            int P { get;}
        }   
        class Middle : ILeft
        {
            int ILeft.P { get { return 0; } }
        }
    
    var mid= new Middle();
    var abc = mid.P // invalid;
    var abc2 = (mid as ILeft).P; //valid