Search code examples
c#genericsinterfaceimplements

C# implementing interfaces with generic type overrides


To simplify my question, I'm using IList and IList<T> as the example. Since IList declared a method Add(object value) and IList<T> declared a method Add(T value). My new class has to have two methods for implementation.

class myList<T> : IList<T>, IList
{
  public void IList.Add(object value)
  {
    this.Add(value as T);
  }
  public void Add(T value)
  {...}
}

Is it possible to avoid such "meaningless" replication?


Solution

  • No you can't avoid this. Because this would violate the principle of interfaces. Think about a client program which just works with IList. This program want to use your class now, which works of course, because you implement IList. So he calls the Method:

    public void IList.Add(object value)
    {
      this.Add(value as T);
    }
    

    What should happen now, if you wouldn't implement this? Sure you can call Add<T> instead, but if there are many classes which implement IList and you call Add-Method on an IList interface to use polymorphism under the hood this would not work anymore.

    C# is strict here for good reason, same as any other language with Interface Concept I know.