Search code examples
c#listinheritanceienumerableenumerable

How to iterates over a List<T> base class within the child class?


I have a collection class that inherits List. I would like a method on that class that can iterate over the items in the base class list.

Currently I have this:

    public class Invoices : List<Invoice>
    {
        public string ToString()
        {
            string cOP = "";
            int i;
            Invoice oInvoice;

            cOP += string.Format("Invoices.Count = {0}\r\n", base.Count);

            foreach (Invoice oInvoice in base)
            {
                cOP += oInvoice.ToString();
            }

            return cOP;
        }
    }

But I get the compile time error on base in the foreach statement, "Use of keyword 'base' is not valid in this context".

I've tried replacing base with:

  • base.ToArray() - this does work, but I thought the whole point of a List is that it is enumerable.
  • base.ToList() - "'System.Collections.Generic.List<SerializerTest.Invoice>' does not contain a definition for 'ToList'"

Is there a reason why I need to convert the List to an Array to iterate over it? Surely I should just be able to iterate over the List?


Solution

  • You should use the this keyword:

    public class Invoices : List<Invoice>
    {
        public string ToString()
        {
            string cOP = "";
            int i;
            Invoice oInvoice;
    
            cOP += string.Format("Invoices.Count = {0}\r\n", base.Count);
    
            foreach (Invoice oInvoice in this)
            {
                cOP += oInvoice.ToString();
            }
    
            return cOP;
        }
    }