0

Could anyone explain why the cast below fails when the implementation of IMyInterface is a struct? I don't get why the runtime cares about the difference between a class and a struct here, given that the List is always a class.

public interface IMyInterface
{
}

public class MyClass : IMyInterface
{
}

public struct MyStruct : IMyInterface
{
}

public static void TestCast<T>()
    where T : IMyInterface
{
    var works = (IEnumerable<IMyInterface>)new List<MyClass>();
    var invalidCastException = (IEnumerable<IMyInterface>)new List<MyStruct>();
}
EM0
  • 5,369
  • 7
  • 51
  • 85
  • 1
    I can't answer why, but you can use the extension method `.AsEnumerable()` instead of the cast to get the desired behavior. – Tomas Aschan Jul 08 '16 at 10:32
  • 1
    Does this answer your question: http://stackoverflow.com/a/9688362/284240 ? `MyStruct` is a value type and `MyClass` is a reference type; covariance only works when both types are reference types. Value types must be boxed. if you cast them to an interface. https://msdn.microsoft.com/en-us/library/25z57t8s(v=vs.90).aspx – Tim Schmelter Jul 08 '16 at 10:38
  • 1
    @TomasLycken - that doesn't work. `.AsEnumerable` is a compile-time error and `.AsEnumerable` still fails to cast to `IEnumerable` – EM0 Jul 08 '16 at 11:48
  • @TimSchmelter yes, it does, thanks very much. I just didn't know the right keywords to search for to find that answer. – EM0 Jul 08 '16 at 11:49

0 Answers0