I have the following:
public interface IEntity
{
IEntityContent Data { get; set; }
}
public interface IEntityContent { }
public interface IThingService<T>
{
void DoThing(T item);
}
public class BaseEntity<T> : IEntity
where T : IEntityContent
{
public abstract T Data { get; set; }
}
public class FooEntity : BaseEntity<FooContent>
{
public override FooContent Data { get; set; }
}
public class FooContent : IEntityContent
{
// Some properties
}
public class ThingService<T> : IThingService<T>
where T : IEntity
{
public void DoThing(T item)
{
Serializer.Instance.Serialize(item.Content);
}
}
The signature of Serializer.Instance.Serialize
is:
string Serialize<T>(T from)
But I get the following:
'BaseEntity<T>' does not implement interface member 'IEntity.Data'. 'BaseEntity<T>.Data' cannot implement 'IEntity.Data' because it does not have the matching return type of 'IEntityContent'
Why is this? As it stands, I am forced to create a bunch of near-identical strongly-typed implementations of IThingService
- which is a shedload of duplication - just to specify different type arguments which, as far as I can see, should be generic.
Is this somehow related to a lack of covariance in BaseEntity
? How can I make ThingService<T>
work?
Why not simply have:
public interface IEntity<T>
{
T Data { get; set; }
}
For an implementation of the interface has to match the interface (as you've not declared any contra/covariance), including the return types (hence your error message)