Here is my code:
public interface ICar
{
CarModel Property { get; set; }
CarModel Method();
}
public Car<T> : ICar where T : CarModel
{
T Property { get; set; }
T Method()
{
//Do Stuff
}
}
I have implemented the interface in my Car<T> class with generic constraints but it doesn't compile with the following error:
Compilation error (line 18, col 15): 'Car<T>' does not implement interface member 'ICar.Property'. 'Car<T>.Property' cannot implement 'ICar.Property' because it does not have the matching return type of 'CarModel'.
Compilation error (line 18, col 15): 'Car<T>' does not implement interface member 'ICar.Method()'. 'Car<T>.Method()' cannot implement 'ICar.Method()' because it does not have the matching return type of 'CarModel'.
I also need the interface to be non generic, here is a .Net fiddle: https://dotnetfiddle.net/m1jDnB
The only work around I have for this is to wrap the property or method with something that implements the interface as it wants it BUT I dont want to do this. ie:
public Car<T> : ICar where T : CarModel
{
T Property { get; set; }
T Method()
{
//Do Stuff
}
CarModel ICar.Property
{
get {return Property; }
set {Property = (CarModel)value; }
}
CarModel ICar.Method()
{
return (CarModel)Method();
}
}
Is there a better way?
Car<MyCarModel>allowed in your design? (MyCarModelinherits fromCarModel)Property = (T)value;instead ofProperty = (CarModel)value. However, that does increase the chances of a run-time error such as the one shown in @recursive's answer