none
List of abstract class RRS feed

  • Question

  • Hi everybody,

    I'm encountering a small problem. I have an abstract class named Model and many derived class (Child1, Child2 ...).

    I would like each derived class to have an ObservableCollection of its own type named ParentList.

    By example, if I create an instance of Child1, I want to have automatically a property named ParentList that can return an ObservableCollection of Child1.

    How can I implement that (if it is possible) without needing to create a property in each derived class ?

    Thanks in advance for your help.

    Have a nice day.

    N.


    • Edited by NicolasC Friday, February 8, 2013 5:21 PM
    Friday, February 8, 2013 5:20 PM

Answers

  • There is no way to directly create and enforce this.  You can do it via generics and convention, however, like so:

    abstract class Model<T> where T: Model
    {
        protected Model()
        {
             this.ParentList = new ObservableCollection<T>();
        }
    
        public ObservableCollection<T> ParentList { get; private set; }
    }
    
    
    // This will now have a ParentList of type OC<Class1>
    class Class1 : Model<Class1>
    {
    }
    
    class Class2 : Model<Class2>
    {
    }

    This works - but it doesn't enforce the type - there's nothing stopping a class Class3 : Model<Class1> from being written..



    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by mark kang Saturday, February 9, 2013 10:26 AM
    • Marked as answer by Mike FengModerator Thursday, February 14, 2013 10:43 AM
    Friday, February 8, 2013 5:30 PM
    Moderator