qingxun su qingxun su - 10 days ago 4
C# Question

How to access a object from List<>

I want to create an List<> of an object to store Guest's base information and have some codes like that

private void btnSave_Click(object sender, EventArgs e)
{
int gender;
string fn;
string ln;
string num;
int bd;
int bm;
int by;

IList<GuestInfo> GuestList = new List<GuestInfo>();
if(tbBirthDate.Text==null||tbBirthMonth==null||tbBirthYear==null||tbFname==null||tbLName==null||tbPhoneNum==null)
{
MessageBox.Show("Please fill in all information");
}
else if (count>=4)
{
MessageBox.Show("You already have 4 members infomation save");
}
else
{
if(radFemale.Checked == true)
{
gender = 0;
}
else
{
gender = 1;
}
fn = tbFname.Text;
ln = tbLName.Text;
num = tbPhoneNum.Text;
bd = Int32.Parse(tbBirthDate.Text);
bm = Int32.Parse(tbBirthMonth.Text);
by = Int32.Parse(tbBirthYear.Text);
GuestList.Add(new GuestInfo(fn,ln,num,gender,bd,bm,by));
}
}
}


GuestInfo:

class GuestInfo
{
private string fName;
private string lName;
private string pNum;
private int Gen;
private int bDate;
private int bMonth;
private int bYear;

public GuestInfo(string FirstName,string LastName, string phoneNum,int Gender, int birthDate,int birthMonth,int birthYear)
{
fName = FirstName;
lName = LastName;
pNum = phoneNum;
Gen = Gender;
bDate = birthDate;
bMonth = birthDate;
bYear = birthYear;

}
}


When the button clicked I store the information, but I don't know how to get a data I wanna use, such as I want to know the First name of Guest on GuestList[1].

Jim Jim
Answer

Your fields are set to private so you can only access them inside the GuestInfo class. To fix that you have to set the modifier to public

public string fName;

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can be accessed only by code in the same class or struct.

Recommendation:

Make properties instead of fields in the GuestInfo class.

  • properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes
  • you can also do other logic, such as validation, when a property is accessed, another useful feature

(In general: Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties)

Set up properties like so to access them for each one:

class GuestInfo
{
    public string fName { get; private set; }

    public GuestInfo(string FirstName)
    {
        fName = FirstName;
    }
}

Then you can access them:

List<GuestInfo> guestList = new List<GuestInfo>();
guestList.Add(new GuestInfo("John"));
guestList.Add(new GuestInfo("Bill"));

var secondGuest = guestList[1].fName;
Comments