Let's code a program sorting friendy and nasty people. All are characters and have a name.
We can represent this as follow :
interface ICharacter
{
string GetName();
}
class Character : ICharacter
{
private readonly string name;
public Character(string name)
{
this.name = name;
}
public string GetName()
{
return this.name;
}
}
class Friendly : Character
{
public Friendly(string name)
: base(name)
{
}
}
class Nasty : Character
{
public Nasty(string name)
: base(name)
{
}
}
Now let's declare and store our characters into a Dictionary this way :
Dictionary<Type, IList<ICharacter>> characters = new Dictionary<Type, IList<ICharacter>>();
characters.Add(typeof(Friendly), new List<ICharacter>() { new Friendly("friendly1"), new Friendly("friendly2") });
characters.Add(typeof(Nasty), new List<ICharacter>() { new Nasty("nasty1"), new Nasty("nasty2") });
Now we can code a method extracting all friendy people from dictionary as a list of friendly people and NOT a list of characters :
public static List<Friendly> GetFriendlyPeople(Dictionary<Type, IList<ICharacter>> allPeople)
{
if (allPeople.TryGetValue(typeof(Friendly), out IList<ICharacter> friendly)) {
return friendly as List<Friendly>; //(List<Friendly>)friendly the same result
}
return new List<Friendly>();
}
Finally, we can call the method GetFriendlyPeople :
List<Friendly> friends = GetFriendlyPeople(characters);
But the return value is null. I tried several combination using interface or not and it's the same result.