views:

81

answers:

4

I am trying to implement a new class inherited from List<string>, to load the contents from a text file to the items.

using System.Collections.Generic;
using System.IO;
using System.Linq;

public class ListExt : List<string>
{
    string baseDirectory;

    public void LoadFromFile(string FileName)
    {
        //does not work because _list is private
        this._items = File.ReadAllLines(FileName).ToList();
    }
}

But I dont know how to load the lines into the _items property because it is private.

Any suggestions?

+6  A: 

Try something like:

public void LoadFromFile(string FileName)
{
    base.AddRange(File.ReadAllLines(FileName));
}
Oskar Kjellin
Which won't compile...
Marc Gravell
Changed it a bit after thinking about it... :)
Oskar Kjellin
Why `base.AddRange` instead of `this.AddRange`?
Fredrik Mörk
Depends on what you want. Sometimes you have implemented a bit more checks etc on the new method that you do not want to call. I know both this and base works here but I think he was going for a pure add and then base is sometimes better. But then again, it does not matter in this case
Oskar Kjellin
+8  A: 

ListExt is the list - so you can just call AddRange on yourself. You can't reassign the list - that would essentially be changing this.

Marc Gravell
A: 

Try this:

AddRange(File.ReadAllLines(FileName).ToList());
Ngu Soon Hui
The ToList() is a waste of memory, an array is an IEnumerable aswell.
Rubys
+1  A: 

No need to derive a whole new class from List<T> over the following line.

List<string> lines = new List<string>(File.ReadAllLines(path));
280Z28