Pinx0 Pinx0 - 2 months ago 15
C# Question

Interface implementation override type of another interface

I have an interface

IArticle
with several implementations:
ProductType
,
RawMaterial
,
PaintType
, etc.

Then I have what I consider a reference (SKU) that is a composite element between an
IArticle
and a
Color
:

public interface IReference
{
Color Color { get; set; }
IArticle Article { get; set; }
}


Then I have several implementations, each one has a corresponding IArticle implementation:


  • Product : IReference
    will have a
    ProductType
    as
    Article
    ,

  • SemifinishedGood: IReference
    will have a
    RawMaterial
    as
    Article

  • Paint : IReference
    will have a
    PaintType
    as
    Article



So the thing is... how can I override the
Article
type, something like this:

public class Paint: IReference
{
public virtual Color Color { get; set; }
public virtual PaintType Article { get; set; }
}


So that I can access
PaintType
specific properties instead of only being an
IArticle
when I'm dealing with a
Paint.Article
without having to cast everytime? What is wrong in this architecture?

Answer

Generic type parameters solve this very easily.

public interface IReference<TArticle> where TArticle : IArticle
{
    Color Color { get; set; }
    TArticle Article { get; set; }
}

public class Paint : IReference<PaintType>
{
    public virtual Color Color { get; set; }
    public virtual PaintType Article { get; set; }
}