Can a class implementing an Interface return is own type

Viewed 58

I'm using .NET CORE 7 Preview and I created a very basic interface :

public interface IRegularPolygon
{
    static readonly int SideCount;

    public RectangleF Bounds { get; }

    public IList<PointF> Points { get; }

    public static abstract IRegularPolygon Create(Point location, int radius);

    public static abstract Point GetCentroid(PointF[] points);
}

Which I implement in a couple a classes. E.G :

class Hexagon : IRegularPolygon
{
    // Working
    public static IRegularPolygon Create(Point location, int radius)
    {
    // Creating the Hexagon
    }

   // Working too, but I would like to avoid casting
   public static IRegularPolygon Create(Point location, int radius)
   {
       // Creating the Hexagon
       return (Hexagon)hexagon;  // still need to cast (Hexagon) when calling this method
   }

   // What I want to achieve.
   // [ERROR] Don't implement IRegularPolygon
   public static Hexagon Create(Point location, int radius)
   {
     // Creating the Hexagon;
     return hexagon // as Hexagon type
   }
}

So, it's working. I can use var hexagon = (Hexagon)Hexgon.Create();

I do understand the compilation error in the method public static Hexagon Create(Point location, int radius).

I was hoping that since I implement the interface, I could return the type itself (Hexagon in that example).

Is this even possible to achieve ? Or should I rather go for a inheritance ?

Thanks for your answers !

Aurélien.

1 Answers

The reason you define an interface is so the caller can know what to expect. To the caller it shouldn't matter what implementation of IRegularPolygon you return. You can return Hexagon if you cast it to IRegularPolygon.

However if you're simply looking to enforce a pattern where every class has a Create method, then an interface is not what you need. Maybe an abstract base class will serve you better:

public abstract class RegularPolygon
{
    public static RegularPolygon Create(Point location, int radius) 
    {
        throw new NotImplementedExecption();
    }
}

public class Hexagon : RegularPolygon
{
    public static new Hexagon Create(Point location, int radius)
    {
        //implement method
    }
}
Related