1

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.

user1364743
  • 5,283
  • 6
  • 51
  • 90

1 Answers1

2

In your dictionary you have two types, Friendly and Nasty.

Th list in Dictionary is a list of ICharacter it not one type its multiable types, that why you gets null.

Try this and you will get an exception that will explane it too you.

 return friendly.Cast<Friendly>().ToList()// here you will get now an exception.

If you want to have your Friendly items is still possible. try this code.

return friendly.Where(x=> x is Friendly).Cast<Friendly>().ToList(); // here you will get your items.
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • The first proposition works and never throw any exception in my exemple because I sort my characters correctly at the beginning when I initialize my dictionary (it's juste an example). I think I could have used the second proposition if I stored all the characters in a simple list of ICharacter as container. Thank you very much ! – user1364743 Apr 16 '20 at 16:10