Home > Net >  c# Add child <list> element at same time as adding parent element
c# Add child <list> element at same time as adding parent element

Time:03-19

Trying to do an add of a class while already doing an add of the parent. I think I have the syntax correct, but not sure how to reference the parent class while doing the child add.

public class address
        {
            public string street_num { get; set; }
            public string street_name { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
            
            public address(string street_num, string street_num, string city,string state,string zip)
            {
                this.street_num = street_num;
                this.street_name = street_name;
                this.city = city;
                this.state = state;
                this.zip = zip;
            }
        }

public class nme
        {
            public string f_name { get; set; }
            public string m_name { get; set; }
            public string s_name{ get; set; }
            public string suffix { get; set; }
            public List<address> addrInfo { get; set; }
        
            public nme(string f_name,string m_name,string s_name, string suffix)
            {
                this.f_name = f_name;
                this.m_name = m_name;
                this.s_name = s_name;
                this.suffix = suffix;
                addrInfo = new List<address>();
            }
        }
        

public List<nme> person = new List<nme>();

static void Main()
        {
            person.Add(new nme("first","middle","last","suffix",**person[].addr**.Add("street_num","street_name","city","state","zip")));
        }

CodePudding user response:

You should input everything you need in the constructor. You can use 'params' to make this slightly neater, i.e.

public nme(string f_name,string m_name,string s_name, string suffix, params address[] addresses){
    addrInfo = new List<address>(addresses);
}

called like

new nme("first","middle","last","suffix",new address("street_num","street_name","city","state","zip"))

I would also using the microsoft suggested naming convensions to make your code easier to read by other developers.

  • Related