W
W
WhiteNinja2017-01-06 15:59:49
ASP.NET
WhiteNinja, 2017-01-06 15:59:49

C#: How to recursively inherit class properties?

Good afternoon!
Please suggest how to implement the following:
There is a BaseItem class :

public abstract class BaseItem
{
  public int Id { get; set; }
  public string Title { get; set; }
  public IEnumerable<BaseItem> Childs { get; set; }
  
  public BaseItem() 
  {
    Childs = new List<BaseItem>();
  }
}

The Item class is inherited from it.
public class Item : BaseItem 
{
  
}

It is necessary that the Childs property of the Item class also contains a list of Item's (itself), and not BaseItem's.
The question is how to organize a recursive property with a list?
Many thanks in advance for any hint!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Silin, 2017-01-06
@byme

Understand me correctly, you need to read the theory about OOP first, etc. Since your question is at the level of a schoolboy who decided to become a programmer for 2-3 weeks.
And in essence, in Childs, you can easily shove both Item and any successor from BaseItem. But if you need only Item in Childs, which is in Item, then generic types will help you here. I'm not going to write the code on how to do this on purpose, because then you will definitely not read anything and ask a bunch of stupid questions. Reading literature is for your own good, you will learn a lot of new and interesting things.

R
Roman, 2017-01-06
@yarosroman

The new modifier will help you

public abstract class BaseItem
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual IEnumerable<BaseItem> Childs { get; set; }

        public BaseItem()
        {
            Childs = new List<BaseItem>();
        }
    }

    public class Item : BaseItem
    {
        public new IEnumerable<Item> Childs { get; set; }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question