I am really confused about object relationships!
I have two classes Person and Address. Here are the details:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
private List<Address> _addresses = new List<Address>();
public void AddAddress(Address address)
{
_addresses.Add(address);
address.Person = this;
}
public List<Address> Addresses
{
get { return _addresses; }
set { _addresses = value; }
}
}
public class Address
{
public string Street { get; set; }
public Person Person
{
get; set;
}
}
The AddAddress method in the Person class adds the address to the Addresses collection and also sets the Person for the Address object. Now, in the code I do the following:
var person = new Person() { FirstName = "John", LastName = "Doe" };
person.AddAddress(new Address() { Street = "Blah Blah" });
person.Addresses[0].Person = null;
I am thinking that it should set the person object to null since Addresses[0].Person is pointing to the original person object. But it is not setting it to null. What is going on here?
Simple Explanation:
A variable, in this case ‘Person’, holds a
referenceto the object. Under the hood, this is just a number. When you assign it to null, what you are doing is just stopping that variable pointing at the object. The object itself still exists.— Edit
A way to understand how this works, is to literally stand near your computer, and point at it. You are now a variable, and your computer is an object. Now stop pointing at the computer (put your arm down). Now you are a variable that has been assigned
null. The computer still exists, nothing has changed about it, the only difference is that you now no-longer point at it.