Search code examples
c#inheritanceprotected

C# Problems acessing protected List from child class


I thought I would be able to access a protected List in a parent class, from a child class, but get the error

Cannot access protected member “Liste.listItems” via a qualifier if type ‘Liste’, the qualifier must be of type ‘ListReader’

Any idea how to overcome this while still maintaining the protection level of the protected List<Object> listItems (so that no other classes but the inherited one can access this List)?

 public class Liste
{
    public string name;
    protected List<Object> listItems = new List<Object>(); //TO DO: add protection
}

class ListReader : Liste
{

    public List<Liste> listsRead = new List<Liste>();

    public List<Liste> ReadLists(TestCaseWorkbook tcwb, string tab)
    {
        try
        {
            int lineID = 0;
            foreach (DataRow row in tcwb.Tables[tab].Rows)
            {
                if (lineID == 0)//first line
                {
                    foreach (DataColumn cell in tcwb.Tables[tab].Columns)
                    {
                        Liste liste = new Liste();
                        liste.name = ExcelWorkbook.CleanTitleToInternal(cell.ColumnName);
                        if(liste.name != "")
                        {
                            listsRead.Add(liste);
                        }                                                   
                    }
                    lineID++;
                }                 
                for (int j = 0; j < row.ItemArray.Length; j++)//rest of sheet
                {
                    Object item = row[j];
                    if(item.ToString() != "")
                    {
                        listsRead[j].listItems.Add(item);
                    }
                }                    
            }

(more code)

The problem is at listsRead[j].listItems.Add(item);


Solution

  • You made field protected, so you have no access to set it in the new class instance. I guess you need to protect only setter, so change this

    protected List<Object> listItems = new List<Object>();
    

    into

    public List<Object> listItems { get; protected set; } = new List<Object>();
    

    and you don't need to inherit from Liste if you don't use neither 'name' nor 'listItems'