Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Classes implementing generic interfaces

Problem Description

I am struggling to get my generic interfaces to work. I have an IContainer<TShape> that takes a list of shapes, where the shapes must implement the IShape<TPoint> interface. The IShape<TPoint> interface has a list of points, where the points must implement the IPoint interface. The part that I am struggling with is the where constraint on the IContainer<TShape> interface.

The error I’m getting is:

The type ‘TPoint’ cannot be used as type parameter ‘TPoint’ in the
generic type or method ‘IShape’. There is no boxing conversion
or type parameter conversion from ‘TPoint’ to
‘Domain.Entities.IPoint’. [Domain]csharp(CS0314)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Interfaces

Container interface:

public interface IContainer<TShape, TPoint> where TShape : IShape<TPoint>
{
    public Guid Id { get; set; }
    public List<TShape<TPoint>> Shapes { get; set; }
}

Shape interface:

public interface IShape<TPoint> where TPoint : IPoint
{
    public Guid Id { get; set; }
    public List<TPoint> Coordinates { get; set; }
}

Point interface:

public interface IPoint
{
    public double X { get; set; }
    public double Y { get; set; }
}

Models

The way I would like my models to work is:

Container model:

public class Container : IContainer<Shape, Point>
{
    public Guid Id { get; set; }
    public List<Shape<Point>> Shapes { get; set; }
}

Shape model:

public class Shape: IShape<Point>
{
    public Guid Id { get; set; }
    public List<Point> Coordinates { get; set; }
}

Point model:

public class Point : IPoint
{
    public double X { get; set; }
    public double Y { get; set; }
}

What syntax is needed to make this work?

>Solution :

I believe the issue is that on IContainer you are only providing a type constraint for TShape, when IShape also requires a type constraint on TPoint.

Try modifying your IContainer interface to the following:

public interface IContainer<TShape, TPoint>
    where TShape : IShape<TPoint>
    where TPoint : IPoint
{
    public Guid Id { get; set; }
    public List<TShape<TPoint>> Shapes { get; set; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading