This is probably a very simple question but I’m a little confused when it comes to working with an object created from a class that contains a field where the type is another class. The part that confuses me is how to populate the field with data from the web form.
For example, if I have a customer class that has a field called contact which is of type Contact, what is the proper way to populate this at the web form level? At present I am doing it as follows and would like to know if this is correct.
This is the code from my customer class and contact is another class.
public class Customer
{
private string firstName;
private string lastName'
private string notes;
private Contact contact;
public Customer()
{
this.contact = new Contact();
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Notes
{
get { return notes; }
set { notes = value; }
}
public Contact Contact
{
get { return contact; }
set { contact = value; }
}
}
Code from my form
private Customer customer;
public WebFormSample()
{
customer = new AddressBook.Customer();
}
protected void addButton_Click(object sender, EventArgs e)
{
customer.FirstName = firstName.Text;
customer.LastName = lastName.Text;
customer.Contact.Phone = phone.Text;
customer.Contact.Email = Email.Text;
}
Is this the way I should be working with the contact object or should I have instantiated a contact object on the web form, populate it and then assign it to contact in the customer object or have I got it completely wrong and this should be done in a completely different way?
Hope this makes sense.
Thanks
Did you try the code you posted? Because I would expect
customer.Contactto benullas you never created an instance for it.So you can fix your existing code like this:
Or you can do as you were asking about:
Depending on your needs, either should work.