-1

I have class

public class Gallery
{
    public string method { get; set; }
    public List<List<object>> gidlist { get; set; }
    public int @namespace { get; set; }
}

Button code

private void button1_Click(object sender, EventArgs e)
{
    List<object> data = new List<object>();
    data.Add(618395);
    data.Add("0439fa3666");

    Gallery jak = new Gallery();
    jak.method = "gdata";
    jak.gidlist.Add(data);
    jak.@namespace = 1;

    string json = JsonConvert.SerializeObject(jak);
    textBox2.Text = json;
}

Here I get System.NullReferenceException. How to add item to gidlist ?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – J. Steen Aug 18 '16 at 11:13

1 Answers1

4

You get it because in now place you initialized the list within jak.

You can:

  1. Add a default constructor and initialize list there:

    public class Gallery
    {
        public Gallery()
        {
            gidlist = new List<List<object>>();
        }
    
        public string method { get; set; }
        public List<List<object>> gidlist { get; set; }
        public int @namespace { get; set; }
    }
    
  2. If in C# 6.0 then you can use the auto-property initializer:

    public List<List<object>> gidlist { get; set; } = new List<List<object>>()
    
  3. If in under C# 6.0 and don't want the constructor option for some reason:

    private List<List<object>> _gidlist = new List<List<object>>(); 
    public List<List<object>> gidlist 
    {
        get { return _gidlist; } 
        set { _gidlist = value; }
    }
    
  4. You can just initialize it before using (I don't recommend this option)

    Gallery jak = new Gallery();
    jak.method = "gdata";
    jak.gidlist = new List<List<object>>();
    jak.gidlist.Add(data);
    jak.@namespace = 1;
    

If before C# 6.0 best practice will be option 1. If 6.0 or higher then option 2.

Graham
  • 7,431
  • 18
  • 59
  • 84
Gilad Green
  • 36,708
  • 7
  • 61
  • 95