Reputation: 319
Lets say I have an class called Person with a constructor
public class Person
{
public string Name { get; set;}
public string Height { get; set; }
public string WhatEverElse { get; set; }
public string Person(string Name, string Height, string WhatEverElse)
{
this.Name = Name;
.......
}
}
Now lets say I want to also include all the pets a person might have.
List<Person> persons = new List<Person>();
persons.Add(new Person("Larry", "5'9", "Whatever"));
foreach(Datarow row in OwnedPets)
{
//push the pet info to the person here
}
Is there a way I can add x amount of pets and pet information to the Person Object? That way I can return Larry with all 2 of his pets or Jerry with all 6 of his pets? Or can I combine two classes an return a list with both?
Upvotes: 2
Views: 56
Reputation: 273
How about a List?
public class Person
{
public string Name { get; set;}
public string Height { get; set; }
public string WhatEverElse { get; set; }
public List<Pet> Pets { get; set; }
public string Person(string Name, string Height, string WhatEverElse)
{
Pets = new List<Pet>();
}
}
public class Pet
{
public string Name { get; set; }
}
You can then add any amount of Pets by assigning new Pets
// For your own sake keep a clear naming convention - just my two bucks
List<Person> persons = new List<Person>();
Person person = new Person("Larry", "5'9", "Whatever");
persons.Add(person);
foreach(Datarow row in OwnedPets)
{
Pet newPet = new Pet();
person.Pets.Add(newPet);
}
Upvotes: 4
Reputation: 2727
Add a Pets list to your person
public class Person
{
public string Name { get; set;}
public string Height { get; set; }
public string WhatEverElse { get; set; }
public List<string> Perts = new List<strings>();
public string Person(string Name, string Height, string WhatEverElse)
{
this.Name = Name;
.......
}
}
now you can add as many pets as you like
Person per = new Person("Larry", "5'9", "Whatever");
per.Pets.Add("Tom");
per.Pets.Add("Jerry");
person.Add(per);
P.S. your list of type Person
should not be named "person" that's super confusing. Call it "persons" or something like that
Upvotes: 3