0

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);
0

4 Answers 4

3

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; }
 }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

1 Comment

This actually worked for me! Thank you! Your explanation was easy to understand, yet helpful :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.