I have the following method in an external class
public static void DoStuffWithAnimals(IDictionary animals)
In my cal
You could modify public static void DoStuffWithAnimals(IDictionary
to add a generic constraint. Here is something that works for me in LINQPad:
void Main()
{
var lions = new Dictionary();
lions.Add("one", new Lion{Name="Ben"});
AnimalManipulator.DoStuffWithAnimals(lions);
}
public class AnimalManipulator
{
public static void DoStuffWithAnimals(IDictionary animals)
where T : Animal
{
foreach (var kvp in animals)
{
kvp.Value.MakeNoise();
}
}
}
public class Animal
{
public string Name {get;set;}
public virtual string MakeNoise()
{
return "?";
}
}
public class Lion : Animal
{
public override string MakeNoise()
{
return "Roar";
}
}