I have this situation:
class Animal
{
int size;
}
class Dog : Animal
{
string Name;
}
class Cat : Animal
{
string Alias;
}
public void Check( Dictionary<string,Animal> animals )
{
foreach(var pet in animals){...}
}
My question is here:
if Dog extends animal why the Ditionary does not recognize a Dog as Animal?
Do you have ideas that allows pass a Dictionary of child class and iterate it (whitout use the treat Dictionary of (string,object) ) ?
public void MySituation()
{
Dictionary<string,Animal> dogs = new Dictionary<string,Dog>();
** ERROR 01**
Dictionary<string,Cat> cats = new Dictionary<string,Cat>();
Check(cats);
** ERROR 02**
}
Thanks very much. That compiler optimization power be with you.
The problem with Dictionary<string,Animal>
is that it allows you to add. If you could add an "animal" to a dictionary of dogs, you could easily end up with a cat in there, then all hell would break loose. So the compiler isn't going to allow you to treat any other type of dictionary as the same.
What you need to do is use an interface that is read-only, such as IEnumerable
.
public void Check( IEnumerable<KeyValuePair<string,Animal>> animals )
{
foreach(var pair in animals)
{
var animal = pair.Value;
//Do something
}
}
The other option is to make your method generic:
public void Check<T>( Dictionary<string,T>> animals ) where T : animal
{
foreach(T animal in animals)
{
//Do something
}
}
If you would like to understand the theory behind this, see one of the answers about covariance and contravariance, like this one or this one.