Newbie
Newbie

Reputation: 361

object reference not set to instance of an object with list

I have a model class which has few properties, one of which is list of integers. I created an instance of this class in the controller and I want to add the ids on some logic to this list. This throws the below error. Can someone help me understand how should the list be initialized? Any help is appreciated, Thanks. Model

Public class A

    {
     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }
    }

Controller

A Info = new A();
Info.itemsForDuplication.Add(relatedItem.Id);

Upvotes: 0

Views: 330

Answers (4)

user4739649
user4739649

Reputation: 1

You can use read/write properties:

class A{

    private List<int> itemForDuplicate;
    public List<int> ItemForDuplicate{
        get{
            this.itemForDuplicate = this.itemForDuplicate??new List<int>();
            return this.itemForDuplicate;
        }
    }
}

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

The reason is that the property, itemsForDuplication has not been set to anything (it is null), yet you are trying to call the Add method on it.

One way to fix this would be to automatically set it in a constructor:

public class A
{
     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }

    public A()
    {
        itemsForDuplication = new List<int>();
    }
}

Alternatively, if you don't use the solution above, you would have to set it on the client side code:

A Info = new A();
Info.itemsForDuplication = new List<int> { relatedItem.Id };

Upvotes: 1

dario
dario

Reputation: 5259

You can add a parameterless constructor to initialize the List:

public class A
{
    public int countT { get; set; }
    public int ID { get; set; }
    public List<int> itemsForDuplication { get; set; }

    public A()
    {
        itemsForDuplication = new List<int>();
    }
}

In this way when you instantiate the object the list gets initialized.

Upvotes: 1

puko
puko

Reputation: 2970

Just create instance of List e.g. in constructor

public class A
{
      public A()
      {
         itemsForDuplication = new List<int>();
      }

     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }
 }

Upvotes: 3

Related Questions