John Tan
John Tan

Reputation: 1385

Implementing an interface with a property that is derived

Say if I have

interface ISomething
{
    Shape Entity { get; set; }
}

and

public class Shape
{ }

public class Circle : Shape
{ }

public class Square : Shape
{ }

How can I achieve something to the effect of:

public class CircleEntity : ISomething
{
    Circle Entity { get; set; }
}

public class SquareEntity: ISomething
{
    Square Entity { get; set; }
}

Since CircleEntity and SquareEntity does not implement Entity as type Shape exactly.

Upvotes: 1

Views: 48

Answers (1)

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

By using generic interface, you can make Entity type variable, which can be defined on derived types.

interface ISomething<T> where T:Shape
{
    T Entity { get; set; }
}

public class CircleEntity : ISomething<Circle>
{
    Circle Entity { get; set; }
}

public class SquareEntity: ISomething<Square>
{
    Square Entity { get; set; }
}

Upvotes: 5

Related Questions