-1

I'm trying to create a new instance of the following model

class Input_Model
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string text {get; set;}
    public string image { get; set; }
    public IList<string> items { get; set; }
    public IList<string> tags { get; set; }
    public string url { get; set; }
    public IList<string> album { get; set; }
}

But when I try to add an item to the items iList I get a null ref exception

Here is the code for creating the new object

        if(!validate_input) { MessageBox.Show("Fields missing"); return; }
        Input_Model new_entry = new Input_Model();
        new_entry.Title = title.Text;
        new_entry.Description = description.Text;
        new_entry.text = text.Text;
        new_entry.image = picture.Text;
        new_entry.items.Add("xxx");  //<--- error occurs here 

I'm pretty sure this happens because it's an iList? but I know that I can't do

items = new iList<string>

So what's the workaround?

  • There is no "workaround" you need to create a `List()`. Your definition is just that - only a definition, not an instance of a list. The answer in the linked duplicate describes _exactly_ your situation. – Jamiec Aug 11 '21 at 09:58
  • hope this help: https://stackoverflow.com/questions/32342188/initializing-list-property-without-new-list-causes-nullreferenceexception – Md. Tazbir Ur Rahman Bhuiyan Aug 11 '21 at 10:01

1 Answers1

2

Input_Model.items is null when you create an instance of Input_Model. Create the list in the constructor:

class Input_Model {
    public Input_Model()
    {
        this.items = new List<string>();
    }

    // Rest of your class
}
Daniel Dearlove
  • 565
  • 2
  • 12