2

Working on a big project, I realized the following snippet :

public interface Mother 
{
    void CoolFeature();
}

public interface Daughter : Mother 
{
}

public class YouJustLostTheGame<T> : List<T> where T : Mother 
{
    public void Crowd(Mother item) 
    {
       this.Add(item); 
    }

    public void useFeature() 
    {
       this.Find(a => { return true; }).CoolFeature(); 
    }
}

fails to compile the Crowd(Mother) function with the message "Unable to convert 'Test.Mother' to 'T'". Of course this seems deeply wrong to me, and the useFeature() is perfectly fine. So what am I missing ?

N.B: VS2012, win7 x64, .NET 4.5

Alberto
  • 15,626
  • 9
  • 43
  • 56
Geod24
  • 883
  • 6
  • 14

2 Answers2

3

The reason it doesn't compile is because it cannot work. Consider

public class MotherClass : Mother
{
    // ...
}

public class DaughterClass : Daughter
{
    // ...
}

void breakThings()
{
    new YouJustLostTheGame<Daughter>().Crowd(new MotherClass());
}

YouJustLostTheGame<Daughter> derives from List<Daughter>. List<Daughter> can only store Daughters. Your Crowd takes a Mother as its parameter, so new MotherClass() is a valid argument. It then attempts to store an item in the list that the list isn't capable of holding.

  • Wow, silly me. That's so obvious once explained. Thanks for cleaning up my friday confusion ! – Geod24 Oct 11 '13 at 07:46
1

You need to change the method signature to accept T instead of mother. crowd(T item)....

Alexandr Mihalciuc
  • 2,537
  • 15
  • 12