I have a struct that implements some interface. This works fine until I have an array of the struct implementation and try to implicitly cast that array to another array of the interface type. (See the below code example)
using System.Collections.Generic;
namespace MainNS
{
public interface IStructInterface
{
string Name { get; }
}
public struct StructImplementation : IStructInterface
{
public string Name
{
get { return "Test"; }
}
}
public class MainClass
{
public static void Main()
{
StructImplementation[] structCollection = new StructImplementation[1]
{
new StructImplementation()
};
// Perform an implicit cast
IEnumerable<IStructInterface> castCollection = structCollection; // Invalid implicit cast
}
}
}
When compiling the above code, I get the error:
error CS0029: Cannot implicitly convert type ‘MainNS.StructImplementation[]’ to ‘MainNS.IStructInterface[]’
If I change StructImplementation to a class I have no problems, so I’m assuming what I’m trying to do is either not valid; or I’m being blind and missing something obvious.
Any advice or explanation for this would be appreciated.
EDIT
In case anyone else has this issue and using a different approach is less than ideal (as was the case in my situation), I worked around my issue using the LINQ method Cast<T>(). So in the example above, I would perform the cast using something like:
IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>();
There is a good article on MSDN about Variance in Generic Types, which I found very useful.
Array variance ony allows for the reference preserving case, and so only works for classes. It is essentially treating the original data as a reference to a different type. This is simply not possible with structs.