Updated with input from MarcinJuraszek
I have a feeling I'm bumping into a co / contra variance problem here, but I'm not sure I understand how to fix it. I have a class like this:
public interface ISomeClass<TEnum, out S>
{
TEnum Dim { get; }
IEnumerable<S> Inc { get; }
}
public class SomeClass<TEnum, S> : ISomeClass<TEnum, S>
where TEnum : struct, IConvertible
where S : IMyInterface
{
public TEnum Dim { get; set; }
public IEnumerable<S> Inc { get; set; }
}
and I have a class that implements IMyInterface
public class MyImplementation : IMyInterface
{
}
And, of course, I have a class with a SomeClass
property:
public class MyContainer<TEnum> where TEnum : struct, IConvertible
{
public SomeClass<TEnum, IMyInterface> MyProp { get; set; }
}
Now my problem is that I can't assign a SomeClass<MyEnum, MyImplementation>
to the MyProp
property because I get an InvalidCastException
at runtime complaining that it can't cast the SomeClass<MyEnum, MyImplementation>
to SomeClass<MyEnum, IMyInterface>
.
How do I work around this?
Example, this doesn't compile:
var c = new MyContainer<MyEnum>();
c.MyProp = new SomeClass<MyEnum, MyImplementation>();
Here's a dot net fiddle