[Solved] How do I manipulate an object’s properties after it has been added to a List in C#


You can get the first item of the list like so:

Person p = pList[0]; or Person p = pList.First();

Then you can modify it as you wish:

p.firstName = "Jesse";

Also, I would recommend using automatic properties:

class public Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string zip { get; set; }

    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

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:

class public Person
{
    private const int ZIP_CODE_LENGTH = 6;
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    private string zip_ = null;
    public string zip 
    { 
        get { return zip_; } 
        set
        {
            if (value.Length != ZIP_CODE_LENGTH ) throw new Exception("Invalid zip code.");
            zip_ = value;
        }
    }

    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

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.

solved How do I manipulate an object’s properties after it has been added to a List in C#