0

When I call the method GetListByName, I get the error ...

Null Exception (object reference not set to an instance of an object.)

... at _ItemListList in the class ItemListList > GetListByName. I don't understand why, the object presets is not empty at this moment. This is not a duplicate because I'm not asking what a NullReferenceException is or how to fix it, my question is more about understanding why the exception is being thrown when I have a valid instance of the ItemListList class.

Item dir1 = new Item("c:\\test1");
Item dir2 = new Item("c:\\test2");

ItemList dirs1 = new ItemList("joe");
dirs1.Add(dir1);
dirs1.Add(dir2);

ItemList dirs2 = new ItemList("solid");
dirs2.Add(dir3);
dirs2.Add(dir4);

presets = new ItemListList();
presets.Add(dirs1);
presets.Add(dirs2);

ItemList myItemList = presets.GetListByName("solid"); 

My Classes:

public class Item
{
    public string Path { get; set; }
    public Item(string Path)
    {
        this.Path = Path;
    }
}


public class ItemList : List<Item>
{
    public ItemList _ItemList { get; set; }
    public string Name { get; set; }
    public ItemList(string Name)
    {
        this.Name = Name;
    }
}



public class ItemListList : List<ItemList>
{
    public ItemListList _ItemListList { get; set; }
    public ItemListList(ItemListList _ItemListList)
    {
        this._ItemListList = _ItemListList;
    }
    public ItemListList()
    {
    }
    public ItemList GetListByName(string Name)
    {
        foreach (ItemList iList in _ItemListList)
        {
            if (iList.Name == Name)
            {
                return iList;
            }
        }
        return null;
    }
}
Kelly S. French
  • 12,198
  • 10
  • 63
  • 93
checkmate
  • 1
  • 1
  • 2
  • 1
    I can't see any `_ItemListList= new ItemListList();` anywhere. How are you creating your `presets` instance? – Pikoh Mar 22 '17 at 12:27
  • I have added the missing code. :) – checkmate Mar 22 '17 at 12:34
  • You have overcomplicated your `ItemListList` class. Remove everything except the `GetListByName` method, and there replace `_ItemListList` with `this`. Should work as expected. BTW i wouldn't have created a new class for this, you have `Extension Methods` for this kind of job – Pikoh Mar 22 '17 at 12:41
  • thank you, it works. thanks also for the info about Extension! – checkmate Mar 22 '17 at 14:00
  • You need to instantiate your _ItemLilstList inside public ItemListList() because that constructor is the one your are calling to create your 'preset' variable. I'm surprised you didn't get an error when you called 'preset.Add()' because that method is not defined in the code you provided. – Kelly S. French Mar 22 '17 at 15:04

0 Answers0