Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...