In my example, I have many classes (Orange
, Pear
, Apple
, ...) that extend a base class Fruit
.
I am creating a model class that contains dictionaries of each type of Fruit
mapped to their integer ids. I'd like to avoid making many field variables like this:
Dictionary<int, Orange> _oranges = new Dictionary<int, Orange>();
I thought I might be able to create a "generic" dictionary, in which I map other dictionaries to Fruit
types:
Dictionary<Type, Dictionary<int, Fruit>> _fruits = new Dictionary<Type, Dictionary<int, Fruit>>();
To insert into this structure, I use a method like so:
public void Insert(Fruit fruit)
{
_fruits[fruit.GetType()][fruit.Id] = fruit;
}
The problem comes when I try to retrieve the stored values, as in this method:
public IEnumerable<T> GetFruits<T>() where T : Fruit
{
return (IEnumerable<T>) _fruits[typeof(T)].Values.ToArray();
}
which would be called like GetFruits<Orange>()
. The cast fails with this error:
System.InvalidCastException: 'Unable to cast object of type 'Example.Fruit[]' to type 'System.Collections.Generic.IEnumerable`1[Example.Orange]'.'
How can I do what I'm trying to do?