Mark Roworth
Mark Roworth

Reputation: 566

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:

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?

Upvotes: 1

Views: 330

Answers (2)

TheGeneral
TheGeneral

Reputation: 81523

Here is a more usual approach

public class Invoices : IEnumerable<Invoice>
{
   private readonly List<Invoice> _invoices = new List<Invoice>();

   public IEnumerator<Invoice> GetEnumerator() => _invoices.GetEnumerator(); 
   IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

   public override string ToString()
   {
      var sb = new StringBuilder();

      sb.AppendLine($"Invoices.Count = {_invoices.Count}");

      foreach (var oInvoice in _invoices)
         sb.Append(oInvoice);

      return sb.ToString();
   }  
}

Just add the methods you need. If you need more list type methods, implement ICollection or IList

Upvotes: 2

Amir
Amir

Reputation: 1274

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;
    }
}

Upvotes: 4

Related Questions