I need some advice/help on this, I can't see the wood from the trees any more.
It's a straight forward series of classes implementing some interfaces using generics.
Then I'm trying to cast the concrete types for example:
MyGenericObject<SomeObject> _obj;
IMyGenericObject<ISomeObject> _genObj = (IMyGenericObject<ISomeObject>)_obj;
// Invalid cast
I've read some articles about covariance and contravariance but not too clear why this wouldn't be possible, or how to get round it?
So, in this example:
public interface IMyObject<in T> where T : IBaseObject
{
T Activity { get; set; }
}
wouldn't work...
....because, you can't get and set the Activity property.
In this example, I needed to do:
public interface IMyObject<out T> where T : IBaseObject
{
T Activity { get; }
}
hope that helps someone, and thanks to all for help!
See Question&Answers more detail:os