Following on from this question Good class design by example I have a follow-up one.
I want to create some collections that are owned by other objects. To recap, I have a Person
class and I want the Person
to be able to have one or more Addresses
. So I thought I would create an Address
class and an Addresses
collection. Make sense? Here's my code so far
class Person
{
public Person(int SSN, string firstName, string lastName)
{
this.SSN = SSN;
FirstName = firstName;
LastName = lastName;
}
public int SSN { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Address
{
public Address(string line1, string postCode)
{
Line1 = line1;
PostCode = postCode;
}
public int ID { get; set; }
public string Line1 { get; set; }
public string PostCode { get; set; }
}
class Addresses : System.Collections.CollectionBase
{
public int Person { get; set; } // should this be of type Person?
public void Add(Address addy)
{
List.Add(addy);
}
public Address Item(int Index)
{
return (Address)List[Index];
}
public void Remove(int index)
{
List.RemoveAt(index);
}
}
How can I associate many addresses with a Person? I'd like to do something like this in Main
:
Person p = new Person(123,"Marilyn","Manson");
Address a = new Address("Somewhere", "blahblah");
p.Addresses.Add(a);
I then want to be able to save the addresses to a database. Should I do Address.Save()
or Addresses.Save()
(or something else)?
How would I change my code to implement that? Thanks for looking.