I’m trying to walk through a bunch of items, each item has an array of List<> objects that I want to convert to an array of arrays.. Here’s the code to do that:
foreach (IngredientNode i in _snapshot._ingredientMap.Values)
{
for (int c = 0; c < NUM_TAGS; c++)
{
if (i.RecipesByTag[c] == null) continue;
i.RecipesByTag[c] = i.RecipesByTag[c].ToArray<RecipeNode>();
} <--- EXCEPTION
}
RecipesByTag has a static type of IEnumerable<RecipeNode>[]. However, its dynamic type is List<RecipeNode>[]. I want to go through each one of those and convert the dynamic type of RecopeNode[]. Under the debugger, this works and i.RecipesByTag gets converted. However, the last curly brace then throws the exception:
Attempted to access an element as a type incompatible with the array.
I have a feeling there’s some sort of stack corruption going on. Can someone explain what’s happening at a technical level here? Thanks!
You shouldn’t have to specify the type argument for the
ToArraymethod, it should be inferred from it’s usage, if you are using strongly typed collections. This is a generic type casting problem. You are trying to put elements in an array of some incompatible type.Your problem should boil to this (these arrays are covariant):
Now, the same thing, with different types (these arrays are also covariant):
It should be obvious why the type system doesn’t like this. Basically, you look at it as if it was an array of
IEnumerable<int>but it’s actually an array ofList<int>. You can not put an unrelated type array of int, into that array.I believe Eric Lippert explains this very well on his blog.