0

I have a problem understanding why terrierPacks in the following code is not recognized as a Collection<Pack<Dog>> ?

public class Dog
{
}

public class Terrier : Dog
{
}

public class Pack<T> where T: Dog
{
}

public class TerrierPack: Pack<Terrier>
{
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var terrierPacks = new ObservableCollection<TerrierPack>();

        //This test is always wrong. Why ?
        if (terrierPacks is Collection<Pack<Dog>>)
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}

Clue: Visual Studio returns the following warning:

The given expression is never of the provided ('System.Collections.ObjectModel.Collection< WpfApplication1.Pack< WpfApplication1.Dog>>') type

David MVVM
  • 109
  • 1
  • 4
  • 1
    Classes are invariant. – Lee Mar 31 '16 at 15:36
  • 2
    The reason being simply that a `Pack` _is not the same type_ as `Pack` and also not derived from it. See http://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase – René Vogt Mar 31 '16 at 15:37

0 Answers0