Reputation: 313
I have the following classes/interfaces:
public interface IConvexPolygon<T> where T : IPositionable
{
IEnumerable<FPVector2> UniqueAxes { get; }
IEnumerable<T> CornerPositionsClockwise { get; }
}
public class ConvexPolygon<T> : ConvexShape, IConvexPolygon<T> where T : IPositionable
{
...
}
public struct Positionable : IPositionable
{
...
}
I now want to cast a ConvexPolygon<Positionable>
to IConvexPolygon<IPositionable>
to be able to use its getters. This throws an invalid cast exception. I tried specifying covariance with out
in the IConvexPolygon interface, with the same result
Upvotes: 0
Views: 107
Reputation: 142233
Variance is applied only to references types, see the docs:
- Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.
So you will need to change Positionable
from struct to class, to make this cast work.
Also if you are planning to work Positionable
via interface take in account that it will be boxed.
Upvotes: 1