0
class temp
{
    public List<table> tables { get; set; }
    public string name { get; set; }
}

class table
{
    public string table { get; set; }
    public string table_type { get; set; }
}

List<temp> lst_temp = new List<temp>();
temp temp = new temp();
temp.name = "CUS";
lst_temp.Add(temp) 

I want add new table in temp.tables but got this error:

Additional information: Object reference not set to an instance of an object.

These are the ways I tried,but still failed, so what I have to do:

table table = new table();
temp tem = lst_temp.SingleOrDefault(x => x.name == "CUS");
tem.tables.Add(syn_table);

or

table table = new table();
lst_temp_syn.Where(x => x.name == "CUS")
  .Select(x => { x.tables.Add(table); return x; })
  .ToList();

or

table table = new table();
foreach (temp tem in lst_temp)
  {
      if(tem.name = "CUS")
        tem.tables.Add(table); 
  }
2
  • Something is wrong here - you cannot have a member name the same as the class name (table) Commented Aug 21, 2017 at 7:56
  • Object type needs to create instant before using it. Commented Aug 21, 2017 at 8:28

1 Answer 1

4

You need to build the tables collection in the constructor of temp or in an initializer:

class temp
{
    public List<table> tables { get; set; }
    public string name { get; set; }

    public temp()
    {
        tables = new List<table>();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or in C#6+: public List<table> tables { get; set; } = new List<table>
@ainwood Yes, that's what I meant by 'or in an initializer'

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.