Grover Grover - 3 months ago 10
C# Question

(C#) Access/Modify Objects in a List

New here, I've been learning c# for about a month.

Anyway, I've been searching StackOverflow for a couple of days now and couldn't find a specific answer to my problem...

//Here's my Class

public class Guy
public static int ID { get; set; }
public static int LifeExpectancy { get; set; }
public static bool Living { get; set; }

public Guy(int id, int lifeExpectancy, bool living)
ID = id;
LifeExpectancy = lifeExpectancy;
Living = living;

What I'm trying to do is create a specific number of "someGuy" objects to then put them into a public list using this method...

public static List<Guy> Guys = new List<Guy>();

public static void makeSomeGuys(int howManyGuys)
for (int i = 0, i <= howManyGuys; i++)
int id = i;
int lifeExpectancy = 80;
bool alive = true;

Guys.Add(New Guy(id, lifeExpectancy, alive));

Console.WriteLine("Made a new Guy {0}", id);

Questions in order of importance:

How do I access a specific object as well as its parameters? (Accessing from the list "Guys".)

How do I access an object from this list in another class? (Not that I absolutely need to, I'm curious)

Can I search for an object in a list by using its parameters? (As opposed to doing something like...

Should I create a new list for objects that have had their parameters modified? (As opposed to leaving it in the original list)

Is it possible to remove items from a list? (Just in general, is that a thing people do? if so, why?)

I really only need the first question answered. The rest of them are just a bonus. Thanks!

Jon Jon

First you need to remove the static modifier from the properties of the Guy class, i.e.:

public int ID { get; set; }
public int LifeExpectancy { get; set; }
public bool Living { get; set; }

because static causes the property to be an attribute of the class itself, rather than the instances of the class (the individual 'guys').

To access life expectancy of the first guy (the zeroth):


To access life expectancy of the fifth guy: