Home > Blockchain >  Classes implementing generic interfaces
Classes implementing generic interfaces

Time:11-18

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)

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?

CodePudding user response:

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; }
}
  •  Tags:  
  • c#
  • Related