0

Until I tried to do this, I assumed that I knew how this worked; however, the following code throws an exception. Because TestOC is a child of ObservableCollection, I thought I could do this:

class MyClass
{
    public string MyProperty { get; set; }
}

class TestOC : ObservableCollection<MyClass>
{

}

class Program
{
    static void Main(string[] args)
    {
        ObservableCollection<MyClass> test = new ObservableCollection<MyClass>();
        test.Add(new MyClass());

        TestOC test2 = (TestOC)test;
    }
}

The error thrown is:

Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[ConsoleApplication17.MyClass]' to type 'ConsoleApplication17.TestOC'.

How can I get the ObservableCollection to assign to my child class here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269

1 Answers1

2

You cannot cast an ObservableCollection<MyClass> to TestOC.

Because it is derived. Meaning TestOC extends ObservableCollection<MyClass>. So if you want to cast an ObservableCollection<MyClass> to TestOC, it is missing the functionality that TestOC adds. (even when the subclass doesn't have anything extra)

But you could cast a TestOC to an ObservableCollection<MyClass>. Because TestOC does implement all what an ObservableCollection<MyClass> implements.


This doesn't work:

TestOC test2 = new ObservableCollection<MyClass>();

This does work:

ObservableCollection<MyClass> test2 = new TestOC();

How can I get the ObservableCollection to assign to my child class here?

You cannot, but there are some options:

1 - Instead of creating a ObservableCollection<MyClass>, you should construct a TestOC. (new TestOC())

2 - If you don't want to write ObservableCollection<MyClass> but a shorter version, you could use aliases, but this doesn't add any functionality. It's only syntactic sugar. This way you could new a TestOC but behind it is a ObservableCollection<MyClass> so fully assignable.

using TestOC = System.Collections.ObjectModel.ObservableCollection<MyClass>;
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57