There must be something fundamental about interfaces/generics I have not yet learned. I hope to learn it now.
Here is the scenario:
I have this interface and class:
public interface IInterface
{
string TestValue { get; set; }
}
public class RealValue: IInterface
{
public string TestValue { get; set; }
}
If I create a method like this it compiles just fine:
public class RandomTest: IMethodInterface
{
public IInterface GetRealValue()
{
RealValue realValue = new RealValue();
return realValue;
}
}
Note that I am returning an object that implements the interface.
Now, if I add to the RandomTest
class a method that returns list then it does not work anymore:
public List<IInterface> GetRealValues()
{
List<RealValue> realValues = new List<RealValue>();
return realValues; // ERROR Here <- says it can't convert to a List<IInterface>
}
So, my guess is that generics can't figure this out, but why?
Is there a way around this? What do you do when the return value of the method above is locked because you are implementing an interface like this:
public interface IMethodInterface
{
IInterface GetRealValue();
List<IInterface> GetRealValues(); // Can't just convert the return types to a concrete
// class because I am implementing this. This
// interface is in a separate project that does not
// have the concrete classes.
}
Is there any hope? What would you do?