SmartK8
SmartK8

Reputation: 2626

Generic implementation of interface

Why isn't this working ?

public interface IPoint
{
  // not important
}

public interface IPointList
{
  List<IPoint> Points { get; }
}

public abstract class Point : IPoint
{
  // implemented IPoint
}

public abstract class PointList<TPointType> : IPointList
  where TPointType: IPoint
{
  public abstract List<TPointType> Points { get; } // <- doesn't compile
}

The TPointType obviously has to be an IPoint. Why this implementation is not allowed ?

regards, Kate

Upvotes: 2

Views: 631

Answers (2)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

As an answer to your comment, on how to get best of both worlds; I was thinking of something like this, where you implement your interface GetPoints property explictily, create a GetPoints property that is 'more typed', and an protected abstract method that you can override in concrete implementations.
The 2 properties call the abstract implementation.

    public abstract class PointList<T> : IPointList where T : IPoint
    {
        public IList<T> GetPoints
        {
            get
            {
                return GetPointsCore ();
            }
        }

        IList<IPoint> IPointList.GetPoints
        {
            get
            {
                return GetPointsCore () as IList<IPoint>;
            }        
        }

        protected abstract IList<T> GetPointsCore();        
    }

Upvotes: 3

krosenvold
krosenvold

Reputation: 77121

The class PointList should implement the IPointList interface. Methods/properties cannot differ by return type only, which is what you're trying to do with the Points declaration in class PointList. If you implement

List<TPointType> Points { get; } 

then logically you cannot implement

List<IPoint> Points { get; }

Because they would differ by return type only.

Upvotes: 2

Related Questions