Say I have a class like this:
class public Person
{
public string firstName;
public string lastName;
public string address;
public string city;
public string state;
public string zip;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
And let’s further say I create a List of type Person like this:
List<Person> pList = new List<Person>;
pList.Add(new Person("Joe", "Smith");
Now, I want to set the address, city, state, and zip for Joe Smith, but I have already added the object to the list. So, how do I set these member variables, after the object has been added to the list?
Thank you.
You can get the first item of the list like so:
Person p = pList[0];orPerson p = pList.First();Then you can modify it as you wish:
p.firstName = "Jesse";Also, I would recommend using automatic properties:
You’ll get the same result, but the day that you’ll want to verify the input or change the way that you set items, it will be much simpler:
Quite possibly not the best decision to just crash when you set a property here, but you get the general idea of being able to quickly change how an object is set, without having to call a
SetZipCode(...);function everywhere. Here is all the magic of encapsulation an OOP.