Say I instantiate a generic class with a covariant type parameter which is a struct
, then I cast the newly created object as itself with a type parameter of object
in the place of struct
, the cast will fail though the variance should allow for it.
Example:
public class Succeeds {}
public struct Fails {}
var castSucceeds = (IEnumerable<object>)Enumerable.Empty<Succeeds>();
var castFails = (IEnumerable<object>)Enumerable.Empty<Fails>();
As you can see from the above this cast works thanks to the generic type of IEnumberable<T>
being covariant, but when attempted with a struct
instead of a class
it fails. I suspect the failure is related to the need for boxing when casting a struct to an object.
Is there any way around this or am I perhaps looking at it wrong?
CodePudding user response:
According to Microsoft:
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.
Try doing a manual cast:
var castFails = Enumerable.Empty<Fails>().Cast<object>();